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
原文地址:https://www.cnblogs.com/sunshisonghit/p/4320393.html