Skip to content

Commit f94ab8a

Browse files
二叉树练习
1 parent 5c7811f commit f94ab8a

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

2.data_structure/1.binary_tree.md

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -108,16 +108,15 @@ class Solution:
108108
else:
109109
last_visit = s.pop()
110110
postorder.append(last_visit.val)
111-
112-
111+
113112
return postorder
114113
```
115114

116115
注意点
117116

118117
- 核心就是:根节点必须在右节点弹出之后,再弹出
119118

120-
DFS 深度搜索-从下向上(分治法)
119+
#### DFS 深度搜索-从下向上(分治法)
121120

122121
```Python
123122
class Solution:
@@ -134,7 +133,8 @@ class Solution:
134133

135134
注意点:
136135

137-
> DFS 深度搜索(从上到下) 和分治法区别:前者一般将最终结果通过指针参数传入,后者一般递归返回结果最后合并
136+
- DFS 深度搜索(从上到下)和分治法区别:前者一般将最终结果通过指针参数传入,后者一般递归返回结果最后合并
137+
- 和后序遍历类似,不过不只处理根节点,要和子节点的处理一起操作。
138138

139139
#### 非递归二叉树通用遍历模板
140140

@@ -371,6 +371,7 @@ class Solution:
371371
> 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
372372
373373
- 思路:分治法,有左子树的公共祖先或者有右子树的公共祖先,就返回子树的祖先,否则返回根节点
374+
- 考虑:后置递归的一种变体,遍历到目标节点后,类似冒泡,往祖先节点传播。当两个节点相遇,就说明找到了公共祖先。
374375

375376
```Python
376377
class Solution:
@@ -393,6 +394,13 @@ class Solution:
393394
return right
394395
else:
395396
return None
397+
398+
# 可以简写为:
399+
# if not left: return right
400+
# if not right: return left
401+
# return root
402+
# 为什么要这么写?考虑左右都找到的情况,这个时候应该返回root。
403+
# 一边为None,另一边不管None还是有节点,都可以直接返回。
396404
```
397405

398406
### BFS 层次应用
@@ -449,7 +457,7 @@ class Solution:
449457
450458
- 思路 1:中序遍历后检查输出是否有序,缺点是如果不平衡无法提前返回结果, 代码略
451459

452-
- 思路 2:分治法,一个二叉树为合法的二叉搜索树当且仅当左右子树为合法二叉搜索树且根结点值大于右子树最小值小于左子树最大值。缺点是若不用迭代形式实现则无法提前返回,而迭代实现右比较复杂
460+
- 思路 2:分治法,一个二叉树为合法的二叉搜索树当且仅当左右子树为合法二叉搜索树且根结点值大于右子树最小值小于左子树最大值。缺点是若不用迭代形式实现则无法提前返回,而迭代实现又比较复杂
453461

454462
```Python
455463
class Solution:
@@ -501,11 +509,12 @@ class Solution:
501509
return True
502510
```
503511

504-
#### [insert-into-a-binary-search-tree](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/)
512+
### [insert-into-a-binary-search-tree](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/)
505513

506514
> 给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。
507515
508-
- 思路:如果只是为了完成任务则找到最后一个叶子节点满足插入条件即可。但此题深挖可以涉及到如何插入并维持平衡二叉搜索树的问题,并不适合初学者。
516+
- 思路:如果只是为了完成任务则找到最后一个叶子节点满足插入条件即可。
517+
- TODO: 但此题深挖可以涉及到如何插入并维持平衡二叉搜索树的问题,并不适合初学者。
509518

510519
```Python
511520
class Solution:
@@ -525,7 +534,7 @@ class Solution:
525534
else:
526535
if node.left is None:
527536
node.left = TreeNode(val)
528-
return root
537+
return root
529538
else:
530539
node = node.left
531540
```
@@ -536,6 +545,8 @@ class Solution:
536545
- 理解 DFS 前序遍历与分治法
537546
- 理解 BFS 层次遍历
538547

548+
解题没有思路时,可以尝试把遍历方法都试一遍,看能否找到规律。
549+
539550
## 练习
540551

541552
- [ ] [maximum-depth-of-binary-tree](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)

0 commit comments

Comments
 (0)