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 };
  • 相关阅读:
    软件测试
    数据库中查询json 样式的值的sql语句
    xml转json的方法
    将数据保存本地文件
    Spring 配置 web.xml (防止spring 内存溢出)
    解决maven工程 子工程中的一些配置读取进来的问题
    quartz 的简单使用
    mock 测试 MVC
    sun 证书问题解决
    将文本转换为json的工具类
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11707121.html
Copyright © 2011-2022 走看看