zoukankan      html  css  js  c++  java
  • 110. Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    可以先求出每个subtree的深度,然后比较。但不高效,时间复杂度为O(nlgn).因为每一次计算左右subtree深度为2*O(lgn), 然后递归n次。

    public bool IsBalanced(TreeNode root) {
            if(root == null) return true;
            int left =  TreeHeight(root.left);
            int right = TreeHeight(root.right);
            if ((left>=right+2)||(left+2<=right)) return false;
            return IsBalanced(root.left)&& IsBalanced(root.right);
        }
        
        public int TreeHeight(TreeNode root)
        {
            if(root == null) return 0;
            if(root.left == null && root.right == null) return 1;
            return Math.Max(TreeHeight(root.left), TreeHeight(root.right))+1;
        }

    优化的方法为DFS,先check更小的subtree是否为Balanced Tree, 如果不是则直接返回false。参考http://www.cnblogs.com/grandyang/p/4045660.html

     public bool IsBalanced(TreeNode root) {
            return !(TreeHeight(root)==-1);
        }
        
        public int TreeHeight(TreeNode root)
        {
            if(root == null) return 0;
            int left = TreeHeight(root.left);
            if(left == -1) return -1;
            int right = TreeHeight(root.right);
            if(right == -1) return -1;
            if ((left>=right+2)||(left+2<=right)) return -1;
            return Math.Max(left, right)+1;
        }
  • 相关阅读:
    《大道至简》读后感
    第一周学习总结-Java
    c++与java的几个不同点
    单调队列 滑动窗口模型
    计算空间
    关于dp初始化问题
    康托展开小结-
    Vm-Ubuntu下配置Qt开发环境
    C++学习013多态
    C++学习012友元
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5863170.html
Copyright © 2011-2022 走看看