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.

描述

给出一棵二叉树,判断是否为平衡二叉树

分析

在求二叉树深度的过程中,判断左右子树是否满足

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {

public boolean isBalanced(TreeNode root) {

return height(root) != -1;
}

private int height(TreeNode root) {

if (root == null) {
return 0;
}

int l = height(root.left);
int r = height(root.right);

if (Math.abs(l - r) > 1 || l == -1 || r == -1) {
return -1;
}

return Math.max(l, r) + 1;
}
}