Balanced Binary Tree

来源:互联网 发布:php架构师面试题 编辑:程序博客网 时间:2024/05/22 13:50

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.

解题思路:首先比较两颗树的高度,比较是不是balance,然后再比较左子树和右子树是不是balance。

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

参考博文http://blog.sina.com.cn/s/blog_71d59f9a01018fyh.html

0 0