LeetCode110.平衡二叉树

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / 
  9  20
    /  
   15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / 
     2   2
    / 
   3   3
  / 
 4   4

返回 false 。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        return help(root) != -1;
    }
    private int help(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int left = help(root.left);
            int right = help(root.right);
            if (left == -1 || right == -1 || Math.abs(left-right) > 1) {
                return -1;
            } else {
                return Math.max(left, right)+1;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/airycode/p/9776456.html