File tree Expand file tree Collapse file tree 3 files changed +53
-3
lines changed Expand file tree Collapse file tree 3 files changed +53
-3
lines changed Original file line number Diff line number Diff line change 46
46
103. 二叉树的锯齿形层序遍历
47
47
104. 二叉树的最大深度
48
48
105. 从前序与中序遍历序列构造二叉树
49
+ 110. 平衡二叉树
49
50
114. 二叉树展开为链表
50
51
115. 不同的子序列
51
52
121. 买卖股票的最佳时机
Original file line number Diff line number Diff line change
1
+ // 110. 平衡二叉树
2
+
3
+
4
+ /**
5
+ * Definition for a binary tree node.
6
+ * public class TreeNode {
7
+ * int val;
8
+ * TreeNode left;
9
+ * TreeNode right;
10
+ * TreeNode() {}
11
+ * TreeNode(int val) { this.val = val; }
12
+ * TreeNode(int val, TreeNode left, TreeNode right) {
13
+ * this.val = val;
14
+ * this.left = left;
15
+ * this.right = right;
16
+ * }
17
+ * }
18
+ */
19
+
20
+
21
+ /*
22
+ 剑指offer 39.平衡二叉树
23
+ 1、本题需要两个递归方法,一个是递归计算每个节点的深度,一个是递归判断每个节点是否平衡
24
+ 2、递归计算节点深度
25
+ 1)方法功能:入参是一个节点,返回该节点的深度
26
+ 2)终止条件:节点为空时返回0
27
+ 3)递归逻辑:左右节点同样需要计算深度,因此调用同样的方法
28
+ 4)返回值:节点的深度 = 1 + max(左节点深度, 右节点深度)
29
+ 3、递归判断每个节点是否平衡
30
+ 1)方法功能:入参是一个节点,返回该节点的左右子树是否平衡
31
+ 2)终止条件:节点为空时返回true
32
+ 3)递归逻辑:调用计算深度的方法得到左右节点的深度,计算高度差是否不超过1,是则平衡返回true,否则不平衡返回false。左右节点同样需要判断是否平衡,因此调用同样的方法
33
+ 4)返回值:
34
+ */
35
+ class Solution {
36
+ public boolean isBalanced (TreeNode root ) {
37
+ if (root == null ) {
38
+ return true ;
39
+ }
40
+ return Math .abs (treeDepth (root .left ) - treeDepth (root .right )) <= 1 && isBalanced (root .left ) && isBalanced (root .right );
41
+ }
42
+
43
+ private int treeDepth (TreeNode root ) {
44
+ if (root == null ) {
45
+ return 0 ;
46
+ }
47
+ return 1 + Math .max (treeDepth (root .left ), treeDepth (root .right ));
48
+ }
49
+ }
Original file line number Diff line number Diff line change @@ -6,16 +6,16 @@ public boolean IsBalanced_Solution(TreeNode root) {
6
6
if (root == null ) {
7
7
return true ;
8
8
}
9
- if (Math .abs (TreeDepth (root .left ) - TreeDepth (root .right )) > 1 ) {
9
+ if (Math .abs (treeDepth (root .left ) - treeDepth (root .right )) > 1 ) {
10
10
return false ;
11
11
}
12
12
return IsBalanced_Solution (root .left ) && IsBalanced_Solution (root .right );
13
13
}
14
14
15
- public int TreeDepth (TreeNode root ) {
15
+ public int treeDepth (TreeNode root ) {
16
16
if (root == null ) {
17
17
return 0 ;
18
18
}
19
- return 1 + Math .max (TreeDepth (root .left ), TreeDepth (root .right ));
19
+ return 1 + Math .max (treeDepth (root .left ), treeDepth (root .right ));
20
20
}
21
21
}
You can’t perform that action at this time.
0 commit comments