Skip to content

Commit 1c5fd38

Browse files
committed
110.平衡二叉树,两个递归
1 parent 7200781 commit 1c5fd38

File tree

3 files changed

+53
-3
lines changed

3 files changed

+53
-3
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
103. 二叉树的锯齿形层序遍历
4747
104. 二叉树的最大深度
4848
105. 从前序与中序遍历序列构造二叉树
49+
110. 平衡二叉树
4950
114. 二叉树展开为链表
5051
115. 不同的子序列
5152
121. 买卖股票的最佳时机

leetcode_Java/Solution0110.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

剑指Offer_Java/Test39.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,16 @@ public boolean IsBalanced_Solution(TreeNode root) {
66
if (root == null) {
77
return true;
88
}
9-
if (Math.abs(TreeDepth(root.left) - TreeDepth(root.right)) > 1) {
9+
if (Math.abs(treeDepth(root.left) - treeDepth(root.right)) > 1) {
1010
return false;
1111
}
1212
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
1313
}
1414

15-
public int TreeDepth(TreeNode root) {
15+
public int treeDepth(TreeNode root) {
1616
if (root == null) {
1717
return 0;
1818
}
19-
return 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right));
19+
return 1 + Math.max(treeDepth(root.left), treeDepth(root.right));
2020
}
2121
}

0 commit comments

Comments
 (0)