forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT5.java
More file actions
34 lines (31 loc) · 687 Bytes
/
Copy pathT5.java
File metadata and controls
34 lines (31 loc) · 687 Bytes
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
/**
* @program JavaBooks
* @description: 平衡二叉树
* @author: mf
* @create: 2020/03/09 17:14
*/
package subject.tree;
/**
* 3
* / \
* 9 20
* / \
* 15 7
* true
*/
public class T5 {
/**
* 自顶向下递归
* @param root
* @return
*/
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1
&& isBalanced(root.left) && isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}