@@ -108,16 +108,15 @@ class Solution:
108
108
else :
109
109
last_visit = s.pop()
110
110
postorder.append(last_visit.val)
111
-
112
-
111
+
113
112
return postorder
114
113
```
115
114
116
115
注意点
117
116
118
117
- 核心就是:根节点必须在右节点弹出之后,再弹出
119
118
120
- DFS 深度搜索-从下向上(分治法)
119
+ #### DFS 深度搜索-从下向上(分治法)
121
120
122
121
``` Python
123
122
class Solution :
@@ -134,7 +133,8 @@ class Solution:
134
133
135
134
注意点:
136
135
137
- > DFS 深度搜索(从上到下) 和分治法区别:前者一般将最终结果通过指针参数传入,后者一般递归返回结果最后合并
136
+ - DFS 深度搜索(从上到下)和分治法区别:前者一般将最终结果通过指针参数传入,后者一般递归返回结果最后合并
137
+ - 和后序遍历类似,不过不只处理根节点,要和子节点的处理一起操作。
138
138
139
139
#### 非递归二叉树通用遍历模板
140
140
@@ -371,6 +371,7 @@ class Solution:
371
371
> 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
372
372
373
373
- 思路:分治法,有左子树的公共祖先或者有右子树的公共祖先,就返回子树的祖先,否则返回根节点
374
+ - 考虑:后置递归的一种变体,遍历到目标节点后,类似冒泡,往祖先节点传播。当两个节点相遇,就说明找到了公共祖先。
374
375
375
376
``` Python
376
377
class Solution :
@@ -393,6 +394,13 @@ class Solution:
393
394
return right
394
395
else :
395
396
return None
397
+
398
+ # 可以简写为:
399
+ # if not left: return right
400
+ # if not right: return left
401
+ # return root
402
+ # 为什么要这么写?考虑左右都找到的情况,这个时候应该返回root。
403
+ # 一边为None,另一边不管None还是有节点,都可以直接返回。
396
404
```
397
405
398
406
### BFS 层次应用
@@ -449,7 +457,7 @@ class Solution:
449
457
450
458
- 思路 1:中序遍历后检查输出是否有序,缺点是如果不平衡无法提前返回结果, 代码略
451
459
452
- - 思路 2:分治法,一个二叉树为合法的二叉搜索树当且仅当左右子树为合法二叉搜索树且根结点值大于右子树最小值小于左子树最大值。缺点是若不用迭代形式实现则无法提前返回,而迭代实现右比较复杂 。
460
+ - 思路 2:分治法,一个二叉树为合法的二叉搜索树当且仅当左右子树为合法二叉搜索树且根结点值大于右子树最小值小于左子树最大值。缺点是若不用迭代形式实现则无法提前返回,而迭代实现又比较复杂 。
453
461
454
462
``` Python
455
463
class Solution :
@@ -501,11 +509,12 @@ class Solution:
501
509
return True
502
510
```
503
511
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/ )
505
513
506
514
> 给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。
507
515
508
- - 思路:如果只是为了完成任务则找到最后一个叶子节点满足插入条件即可。但此题深挖可以涉及到如何插入并维持平衡二叉搜索树的问题,并不适合初学者。
516
+ - 思路:如果只是为了完成任务则找到最后一个叶子节点满足插入条件即可。
517
+ - TODO: 但此题深挖可以涉及到如何插入并维持平衡二叉搜索树的问题,并不适合初学者。
509
518
510
519
``` Python
511
520
class Solution :
@@ -525,7 +534,7 @@ class Solution:
525
534
else :
526
535
if node.left is None :
527
536
node.left = TreeNode(val)
528
- return root
537
+ return root
529
538
else :
530
539
node = node.left
531
540
```
@@ -536,6 +545,8 @@ class Solution:
536
545
- 理解 DFS 前序遍历与分治法
537
546
- 理解 BFS 层次遍历
538
547
548
+ 解题没有思路时,可以尝试把遍历方法都试一遍,看能否找到规律。
549
+
539
550
## 练习
540
551
541
552
- [ ] [ maximum-depth-of-binary-tree] ( https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/ )
0 commit comments