0%

平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

解答

还有优化空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
int left = deepth(root.left) + 1;
int right = deepth(root.right) + 1;

return Math.abs(left - right) <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}

private int deepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = deepth(root.left) + 1;
int right = deepth(root.right) + 1;

return Math.max(left, right);
}