首页 > 代码库 > Balanced Binary Tree

Balanced Binary Tree

Note:
a balaced tree needs to be balaced all the time. So it is important remember the status of each subtree. If it is not balaced in the middle, the full tree is not balaced. For example, this tree is not balaced: {1,2,3,4,#,5,6,7,8,9,10,11,12}

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    private class ResultType {
        public int depth;
        public boolean isBalanced;
        public ResultType(int depth, boolean isBalanced) {
            this.depth = depth;
            this.isBalanced = isBalanced;
        } 
    } 
    public boolean isBalanced(TreeNode root) {
        // write your code here
        if (root == null) {
            return true;
        }
        
        return helper(root).isBalanced;
    }
    
    private ResultType helper(TreeNode root) {
        if (root == null) {
            return new ResultType(0, true);
        }
        
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        
        if (Math.abs(left.depth - right.depth) <= 1 && left.isBalanced && right.isBalanced) {
            return new ResultType(Math.max(left.depth, right.depth) + 1, true);
        } else {
            //System.out.println(root.val);
            return new ResultType(Math.max(left.depth, right.depth) + 1, false);
        }
        
    }
}

 

Balanced Binary Tree