zoukankan      html  css  js  c++  java
  • 剑指offer——61平衡二叉树

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    题解:
      方法一:使用深度遍历,判断每个节点是不是平衡二叉树,这种从上至下的方法会导致底层的节点重复判断多次
      方法二:使用后序遍历判断,这种方法为自下而上,每个节点只需要判断一次即可
     
      
     1 //方法一:使用深度遍历,判断每个节点是不是平衡二叉树,这种从上至下的方法会导致底层的节点重复判断多次
     2 class Solution01 {
     3 public:
     4     bool IsBalanced_Solution(TreeNode* pRoot) {
     5         if (pRoot == nullptr)return true;
     6         int left = getHeight(pRoot->left);
     7         int right = getHeight(pRoot->right);
     8         if (abs(left - right) > 1)return false;
     9         return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    10     }
    11 private:
    12     int getHeight(TreeNode *pRoot)
    13     {
    14         if (pRoot == nullptr)return 1;
    15         int left = getHeight(pRoot->left);
    16         int right = getHeight(pRoot->right);
    17         return max(left, right) + 1;
    18     }
    19 };
    20 
    21 //方法二:使用后序遍历判断,这种方法为自下而上,每个节点只需要判断一次即可
    22 class Solution02 {
    23 public:
    24     bool IsBalanced_Solution(TreeNode* pRoot) {
    25         if (pRoot == nullptr)return true;
    26         int level = 0;
    27         return IsBalanced_Solution(pRoot, level);
    28     }
    29 private:
    30     bool IsBalanced_Solution(TreeNode* pRoot, int &level)
    31     {
    32         if (pRoot == nullptr)
    33         {
    34             level = 0;
    35             return true;
    36         }
    37         //按照后序遍历去判断左右子树,然后以当前节点为根树的深度
    38         int left = 0, right = 0;
    39         if (IsBalanced_Solution(pRoot->left, left) && IsBalanced_Solution(pRoot->right, right))
    40         {
    41             if (abs(left - right) <= 1)
    42             {
    43                 level = max(left, right) + 1;
    44                 return true;
    45             }
    46         }
    47         return false;
    48     }
    49 };
  • 相关阅读:
    virtualbox+vagrant学习-2(command cli)-19-vagrant box命令
    virtualbox+vagrant学习-2(command cli)-24-Aliases别名
    virtualbox+vagrant学习-2(command cli)-23-vagrant version命令
    virtualbox+vagrant学习-2(command cli)-22-vagrant validate命令
    如何快速学习一门技术或进入一个岗位
    EL表达式详解
    关于JSP乱码问题
    java mail使用qq邮箱发邮件的配置方法
    数据库命名规范
    java中的Serializable接口的作用
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11707121.html
Copyright © 2011-2022 走看看