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.

现在发现做这种递归解树的问题是最简单的问题了- -!,

一次AC,代码如下:

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null)
        	return true;
        int leftHeight=getDepth(root.left);
        int rightHeight=getDepth(root.right);
        if(Math.abs(leftHeight-rightHeight)>1)
        	return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
	
	public int getDepth(TreeNode root){
		if(root==null)
			return 0;
		int leftHeight=getDepth(root.left);
		int rightHeight=getDepth(root.right);
		return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
	}
}


你可能感兴趣的:(java,LeetCode,tree)