Balanced Binary Tree

来源:互联网 发布:mac os x 10.12.6镜像 编辑:程序博客网 时间:2024/06/16 02:35
Problem:

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.


Solution:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   boolean isBalance = true;
    public boolean isBalanced(TreeNode root) {
        balanceCheck(root);
        return isBalance;
    }
    
    private int balanceCheck(TreeNode root)
    {
         if(!isBalance || root==null)
             return 0;
    
         int ldep,rdep;
         ldep = balanceCheck(root.left);
         rdep = balanceCheck(root.right);
    
         if(Math.abs(ldep-rdep)>1)
             isBalance = false;
    
         return Math.max(ldep, rdep)+1;
    }
}
0 0
原创粉丝点击