[leetcode]Balanced Binary Tree

经过之前的某题的经验(http://www.cnblogs.com/lautsie/p/3249723.html),这次稍微顺利了点。不过一开始没理解平衡二叉树的概念,应该是对每个左子树和右子树的高度差距不超过一,而不是所有叶子节点的高度不超过一。

算法是递归,高度是要递归算的,然后把结果作为引用去更新。

public class Solution {
    public boolean isBalanced(TreeNode root) {
        boolean[] balanced = new boolean[1];
        balanced[0] = true;
        getHeight(root, balanced);
        return balanced[0];
    }
    
    public int getHeight(TreeNode root, boolean[] balanced){
        if (root == null) return 0;
        int hl = getHeight(root.left, balanced);
        int hr = getHeight(root.right, balanced);
        if (Math.abs(hl-hr) > 1) balanced[0] = false;
        return Math.max(hl, hr) + 1;
    }
}

 在这个解答里,将boolean结果作为返回值,而高度作为引用,可以做到在false时第一时间返回。

http://blog.csdn.net/xshalk/article/details/8150030

另外有个后序遍历的方法也可以:http://zhedahht.blog.163.com/blog/static/25411174201142733927831/

原文地址:https://www.cnblogs.com/lautsie/p/3268769.html