Commit da5c2f0 1 parent a234603 commit da5c2f0 Copy full SHA for da5c2f0
File tree 3 files changed +10
-0
lines changed
3 files changed +10
-0
lines changed Original file line number Diff line number Diff line change @@ -282,6 +282,8 @@ void traverse(TreeNode root) {
282
282
}
283
283
```
284
284
285
+ <visual slug =' mydata-maxdepth1 ' title =' 遍历思路的可视化 ' />
286
+
285
287
这个解法应该很好理解,但为什么需要在前序位置增加 ` depth ` ,在后序位置减小 ` depth ` ?
286
288
287
289
因为前面说了,前序位置是进入一个节点的时候,后序位置是离开一个节点的时候,` depth ` 记录当前递归到的节点深度,你把 ` traverse ` 理解成在二叉树上游走的一个指针,所以当然要这样维护。
@@ -310,6 +312,8 @@ int maxDepth(TreeNode root) {
310
312
}
311
313
```
312
314
315
+ <visual slug =' mydata-maxdepth2 ' title =' 分解问题思路的可视化 ' />
316
+
313
317
只要明确递归函数的定义,这个解法也不难理解,但为什么主要的代码逻辑集中在后序位置?
314
318
315
319
因为这个思路正确的核心在于,你确实可以通过子树的最大深度推导出原树的深度,所以当然要首先利用递归函数的定义算出左右子树的最大深度,然后推出原树的最大深度,主要逻辑自然放在后序位置。
@@ -548,6 +552,8 @@ class Solution {
548
552
}
549
553
```
550
554
555
+ <visual slug =' mydata-diameter-of-binary-tree ' />
556
+
551
557
这下时间复杂度只有 ` maxDepth ` 函数的 O(N) 了。
552
558
553
559
讲到这里,照应一下前文:遇到子树问题,首先想到的是给函数设置返回值,然后在后序位置做文章。
Original file line number Diff line number Diff line change @@ -341,6 +341,8 @@ void flatten(TreeNode root) {
341
341
}
342
342
```
343
343
344
+ <visual slug =' flatten-binary-tree-to-linked-list ' />
345
+
344
346
你看,这就是递归的魅力,你说 ` flatten ` 函数是怎么把左右子树拉平的?
345
347
346
348
不容易说清楚,但是只要知道 ` flatten ` 的定义如此并利用这个定义,让每一个节点做它该做的事情,然后 ` flatten ` 函数就会按照定义工作。
Original file line number Diff line number Diff line change @@ -93,6 +93,8 @@ int removeDuplicates(int[] nums) {
93
93
}
94
94
```
95
95
96
+ <visual slug =' remove-duplicates-from-sorted-array ' />
97
+
96
98
算法执行的过程如下 GIF 图:
97
99
98
100
![ ] ( https://labuladong.github.io/pictures/数组去重/1.gif )
You can’t perform that action at this time.
0 commit comments