题目:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:
1.
最直接的做法,遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
classSolution {
public
boolean
IsBalanced_Solution(TreeNode root) {
if
(root ==
null
) {
return
true
;
}
return
Math.abs(maxDepth(root.left) - maxDepth(root.right)) <=
1
&&
IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private
int
maxDepth(TreeNode root) {
if
(root ==
null
) {
return
0
;
}
return
1
+ Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public
class
Solution {
public
boolean
IsBalanced_Solution(TreeNode root) {
return
getDepth(root) != -
1
;
}
private
int
getDepth(TreeNode root) {
if
(root ==
null
) {
return
0
;
}
int
leftHeight = getDepth(root.left);
if
(leftHeight == -
1
) {
return
-
1
;
}
int
rightHeight = getDepth(root.right);
if
(rightHeight == -
1
) {
return
-
1
;
}
return
Math.abs(leftHeight - rightHeight) >
1
? -
1
:
1
+ Math.max(leftHeight, rightHeight);
}
}
|