Balanced Binary Tree

Balanced Binary Tree 

问题:

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.

思路:

  典型的dfs

我的代码:

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

 

posted on 2015-03-07 15:10  zhouzhou0615  阅读(179)  评论(0编辑  收藏  举报

导航