Update notes
ci/woodpecker/push/test Pipeline was successful Details

This commit is contained in:
Sainnhe Park 2023-02-01 13:11:44 +08:00
parent e4ec64865b
commit a5dd365883
2 changed files with 9 additions and 0 deletions

View File

@ -73,3 +73,4 @@ struct TreeNode {
1. 深度优先搜索从下往上,广度优先搜索从上往下,所以如果需要处理从上往下并且状态积累的情形 (e.g. [s0404](https://leetcode.cn/problems/sum-of-left-leaves/) && [s0257](https://leetcode.cn/problems/binary-tree-paths/)) 可以先创建一个结构体用来描述节点状态,然后用 BFS 遍历。
2. 写递归时,如果 `TreeNode *ptr` 不足以描述当前节点状态,则可以写一个辅助函数,接收 `TreeNode *ptr` 为参数,返回 `TreeNodeState` 来描述当前节点的状态。参考 [s0098](https://leetcode.cn/problems/validate-binary-search-tree/)
3. 另一种需要结构体的地方是需要获得每个节点路径(即根节点到当前节点所经过的路径),可以用 DFS 或 BFS 遍历。
4. 如果要处理不是从上往下积累状态而是按照一定规则遍历节点并积累状态的情况e.g. [s0538](https://leetcode.cn/problems/convert-bst-to-greater-tree/description/))则考虑用三种递归遍历方式中的一种来遍历,并用一个全局变量来记录遍历状态。另外,务必理解并记忆每种遍历方式的动态图!

View File

@ -29,6 +29,8 @@ void main(void) {
前中后序遍历的区别就在于访问节点的顺序不同。
**注意**:务必理解和记忆每种遍历的遍历动态图!
前序遍历:
```cpp
@ -37,6 +39,8 @@ void main(void) {
dfs(curNode->right, result);
```
![begin](https://paste.sainnhe.dev/cSaJ.gif)
中序遍历:
```cpp
@ -45,6 +49,8 @@ void main(void) {
dfs(curNode->right, result);
```
![medium](https://paste.sainnhe.dev/KJMD.gif)
后序遍历:
```cpp
@ -53,6 +59,8 @@ void main(void) {
printf("%d\n", curNode->val);
```
![end](https://paste.sainnhe.dev/PHbJ.gif)
## 深度优先遍历(迭代法)
由于递归本质是对栈进行操作,因此也可以用迭代+栈的方式实现。