Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from labuladong:master #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 1 commit into AlgorithmAndLeetCode:master from labuladong:master
May 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions 数据结构系列/二叉树总结.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,8 @@ void traverse(TreeNode root) {
}
```

<visual slug='mydata-maxdepth1' title='遍历思路的可视化' />

这个解法应该很好理解,但为什么需要在前序位置增加 `depth`,在后序位置减小 `depth`?

因为前面说了,前序位置是进入一个节点的时候,后序位置是离开一个节点的时候,`depth` 记录当前递归到的节点深度,你把 `traverse` 理解成在二叉树上游走的一个指针,所以当然要这样维护。
Expand Down Expand Up @@ -310,6 +312,8 @@ int maxDepth(TreeNode root) {
}
```

<visual slug='mydata-maxdepth2' title='分解问题思路的可视化' />

只要明确递归函数的定义,这个解法也不难理解,但为什么主要的代码逻辑集中在后序位置?

因为这个思路正确的核心在于,你确实可以通过子树的最大深度推导出原树的深度,所以当然要首先利用递归函数的定义算出左右子树的最大深度,然后推出原树的最大深度,主要逻辑自然放在后序位置。
Expand Down Expand Up @@ -548,6 +552,8 @@ class Solution {
}
```

<visual slug='mydata-diameter-of-binary-tree'/>

这下时间复杂度只有 `maxDepth` 函数的 O(N) 了。

讲到这里,照应一下前文:遇到子树问题,首先想到的是给函数设置返回值,然后在后序位置做文章。
Expand Down
2 changes: 2 additions & 0 deletions 数据结构系列/二叉树系列1.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,8 @@ void flatten(TreeNode root) {
}
```

<visual slug='flatten-binary-tree-to-linked-list' />

你看,这就是递归的魅力,你说 `flatten` 函数是怎么把左右子树拉平的?

不容易说清楚,但是只要知道 `flatten` 的定义如此并利用这个定义,让每一个节点做它该做的事情,然后 `flatten` 函数就会按照定义工作。
Expand Down
2 changes: 2 additions & 0 deletions 算法思维系列/双指针技巧.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ int removeDuplicates(int[] nums) {
}
```

<visual slug='remove-duplicates-from-sorted-array' />

算法执行的过程如下 GIF 图:

![](https://labuladong.github.io/pictures/数组去重/1.gif)
Expand Down

AltStyle によって変換されたページ (->オリジナル) /