Balanced Binary Tree

https://leetcode.com/problems/balanced-binary-tree/

https://leetcode.com/discuss/28162/java-o-n-solution-based-on-maximum-depth-of-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.

public class Solution {
private boolean result = true;

public boolean isBalanced(TreeNode root) {
    maxDepth(root);
    return result;
}

public int maxDepth(TreeNode root) {
    if (root == null)
        return 0;
    int l = maxDepth(root.left);
    int r = maxDepth(root.right);
    if (Math.abs(l - r) > 1)
        result = false;
    return 1 + Math.max(l, r);
}
}
 1 public class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         if (root == null)
 4             return true;
 5         if (Math.abs(height(root.left)-height(root.right)) <= 1)
 6             return (isBalanced(root.left) && isBalanced(root.right));
 7         return false;
 8     }
 9     public int height(TreeNode root) {
10         if (root == null)
11             return 0;
12         int left = height(root.left);
13         int right= height(root.right);
14         return (Math.max(left,right)+1);
15 
16     }
17 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4479671.html