• 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;
        }
  • 相关阅读:
    CH6301 疫情控制
    [BeiJing2010组队]次小生成树 Tree
    CH6303 天天爱跑步
    CH6302 雨天的尾巴
    POJ3417 Network
    Problem 1999. -- [Noip2007]Core树网的核
    [Apio2010]patrol 巡逻
    「TJOI2018」str
    NOI2018 你的名字
    BZOJ5137 [Usaco2017 Dec]Standing Out from the Herd
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5863170.html
Copyright © 2020-2023  润新知