forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
45 lines (41 loc) · 956 Bytes
/
Solution.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @author Anonymous
* @since 2019/12/10
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean isBalanced;
/**
* 判断是否是平衡二叉树
*
* @param root 二叉树根结点
* @return 是否是平衡二叉树
*/
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
isBalanced = true;
treeDepth(root);
return isBalanced;
}
private int treeDepth(TreeNode root) {
if (root == null || !isBalanced) {
return 0;
}
int lDepth = treeDepth(root.left);
int rDepth = treeDepth(root.right);
if (Math.abs(lDepth - rDepth) > 1) {
isBalanced = false;
}
return 1 + Math.max(lDepth, rDepth);
}
}