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

    平衡二叉树

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    平衡二叉树的概念:为空树,或者左右两边的高度差不超过1

    自己想的笨方法:从根部开始,采用前序遍历法,依次求左右子树的深度,然后求它们的差,遇到不符合要求的结点的返回false,否则递归的进行后续子结点的高度的求解

    IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);

    public class Solution {
        public boolean IsBalanced_Solution(TreeNode root) {
            if(root == null) return true;
            while(root != null){
                int left = deep(root.left);
                int right = deep(root.right);
                if(Math.abs(left - right) > 1) return false;
                return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
            }
            return true;
        }
        
        public int deep(TreeNode root){
            if(root == null) return 0;
            return 1 + Math.max(deep(root.left), deep(root.right));
        }
    }
    

      

    注:上面的方法有个缺点:就是从上往下依次求解的话,会对于每个节点的深度都求解多次,增加不必要的开销。

    别人的思路:从下往上的递归求解结点的高度差,若有不符合要求的,则返回false,否则递归向上求解子结点的高度。 

    而从下往上递归时,是使用后序遍历法来进行求解的

    每次都判断左右子树的高度差,若不符合left-right>1的话,则返回-1;

    public class Solution {
        public boolean IsBalanced_Solution(TreeNode root) {
            if(root == null) return true;
             return deep(root) != -1;
        }
        public int deep(TreeNode root){
            if(root == null){
                return 0;
            }
            int left = deep(root.left);
            if(left == -1) return -1;
            int right = deep(root.right);
            if(right == -1) return -1;
            return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1;
        }
    }
    

      

  • 相关阅读:
    单片机基础
    EM310_AT收到的短信分析
    [原]改动CImage以实现以指定的质量保存Jpeg图像
    [原创]巧用DOS命令改子目录中的文件名
    二个月零七天,我女儿会翻身了
    [原]用正则得到HTML中所有的图片路径
    新文章:把程序放在相册中
    [原]用三行代码实现对音量的控制,实现增大,减小,静音
    BIOS中隐藏Telnet后门
    CoolChm 注册机的编写
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8680791.html
Copyright © 2011-2022 走看看