5 - Binary Tree & Tree-based DFS

93. Balanced Binary Tree

https://www.lintcode.com/problem/balanced-binary-tree/description?_from=ladder&&fromId=1

分治法:

方法一: with ResultType

class ResultType {
    boolean isBalanced;
    int maxDepth;
    ResultType(boolean isBalanced, int maxDepth) {
        this.isBalanced = isBalanced;
        this.maxDepth = maxDepth;
    }
}
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    public boolean isBalanced(TreeNode root) {
        // write your code here
        return helper(root).isBalanced;
    }
    
    public ResultType helper(TreeNode root) {
        if(root == null) {
            return new ResultType(true, 0);
        }
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        if(!left.isBalanced || !right.isBalanced) {
            return new ResultType(false, Math.max(left.maxDepth, right.maxDepth) + 1);
        }
        if(Math.abs(left.maxDepth - right.maxDepth) > 1) {
            return new ResultType(false, Math.max(left.maxDepth, right.maxDepth) + 1);
        }
        return new ResultType(true, Math.max(left.maxDepth, right.maxDepth) + 1);
    }
}

方法二:

 

posted @ 2019-05-10 09:31  Jenna777  阅读(85)  评论(0编辑  收藏  举报