Balanced Binary Tree

来源:互联网 发布:linux 纯文本档 高亮 编辑:程序博客网 时间:2024/06/05 00:11

https://oj.leetcode.com/problems/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 ofevery node never differ by more than 1.

 public boolean isBalanced(TreeNode root)


这题看过CC150的人可能都会有一个误区,这个误区我用下面一段代码来表述:

    public boolean isBalanced(TreeNode root) {        return maxDepth(root) - minDepth(root) <= 1;    }        public int maxDepth(TreeNode root){        if(root == null)            return 0;        else            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;    }        public int minDepth(TreeNode root){         if(root == null)             return 0;         else             return Math.min(minDepth(root.left), minDepth(root.right)) + 1;     }

这段代码是错的。因为这代码判断的是完全二叉树,而不是平衡二叉树。平衡二叉树表示的是任意两棵子树的MaxDepth差不超过一就可以了。和这种完全二叉树还是有很大意义上的区别的。而这一题,是要比看上去稍微难那么一点点的。原因就在于它需要在每一棵子树上用一种自下向上的递归方法同时返回这棵子树左右两端的MaxDepth的同时也要返回这两棵子树是否isBalanced的。也就是此题暗含的另一个条件就是:平衡二叉树的所有子树都是平衡二叉树,只要有一个节点不对,那就全盘都不对了。要同时返回一个boolean和一个integer,看上去只能新开一个class来包含这两个元素了。但其实我们可以巧妙的用特殊的int来同时做到两点。事实上如果在某一点上我们判断出false的值,那么就没有必要再往上返回高度了。相反返回一个不可能达到的值譬如Integer.MIN_VALUE表示false就可以了。下面就给出代码:

    public boolean isBalanced(TreeNode root) {        return depth(root) != Integer.MIN_VALUE;//一旦返回的是实际的高度而不是MIN_VALUE就表示检测通过了    }        public int depth(TreeNode root){        if(root == null)            return 0;        int left = depth(root.left);        int right = depth(root.right);        if(left == Integer.MIN_VALUE || right == Integer.MIN_VALUE)//两边有一边已经出错了。            return Integer.MIN_VALUE;        else if(Math.abs(left - right) <= 1)//高度差小于1,继续返回高度。            return Math.max(left, right) + 1;        else            return Integer.MIN_VALUE;//高度差大于1。出错    }



0 0