• 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;
        }
  • 相关阅读:
    MySQL 待解决死锁
    MySQL5.7 服务 crash 后无法启动
    MySQL Group Replication
    MySQL容量规划之tcpcopy应用之道
    Python模块安装路径初探
    MySQL5.7多源复制实践
    Mysql中两个select语句的连接
    ThinkPhp sql语句执行方法
    TP框架如何绑定参数。目的进行ajax验证
    jquery 复合事件 toggle()方法的使用
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5863170.html
Copyright © 2020-2023  润新知