refactor: 优化二叉树的递归遍历.md

This commit is contained in:
qiufeihong2018
2024-04-25 17:34:06 +08:00
parent 1f94655e9a
commit f755ecc5fc

View File

@ -48,7 +48,7 @@ void traversal(TreeNode* cur, vector<int>& vec)
if (cur == NULL) return;
```
3. **确定单层递归的逻辑**:前序遍历是中左右的序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下:
3. **确定单层递归的逻辑**:前序遍历是中左右的序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下:
```cpp
vec.push_back(cur->val); // 中
@ -287,52 +287,91 @@ func postorderTraversal(root *TreeNode) (res []int) {
前序遍历:
```Javascript
var preorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null)return ;
//先序遍历所以从父节点开始
res.push(root.val);
//递归左子树
dfs(root.left);
//递归右子树
dfs(root.right);
}
//只使用一个参数 使用闭包进行存储结果
dfs(root);
return res;
// 第一种
// let res=[];
// const dfs=function(root){
// if(root===null)return ;
// //先序遍历所以从父节点开始
// res.push(root.val);
// //递归左子树
// dfs(root.left);
// //递归右子树
// dfs(root.right);
// }
// //只使用一个参数 使用闭包进行存储结果
// dfs(root);
// return res;
// 第二种
return root
? [
// 前序遍历:中左右
root.val,
// 递归左子树
...preorderTraversal(root.left),
// 递归右子树
...preorderTraversal(root.right),
]
: [];
};
```
中序遍历
```javascript
var inorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null){
return ;
}
dfs(root.left);
res.push(root.val);
dfs(root.right);
}
dfs(root);
return res;
// 第一种
// let res=[];
// const dfs=function(root){
// if(root===null){
// return ;
// }
// dfs(root.left);
// res.push(root.val);
// dfs(root.right);
// }
// dfs(root);
// return res;
// 第二种
return root
? [
// 中序遍历:左中右
// 递归左子树
...inorderTraversal(root.left),
root.val,
// 递归右子树
...inorderTraversal(root.right),
]
: [];
};
```
后序遍历
```javascript
var postorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null){
return ;
}
dfs(root.left);
dfs(root.right);
res.push(root.val);
}
dfs(root);
return res;
// 第一种
// let res=[];
// const dfs=function(root){
// if(root===null){
// return ;
// }
// dfs(root.left);
// dfs(root.right);
// res.push(root.val);
// }
// dfs(root);
// return res;
// 第二种
// 后续遍历:左右中
return root
? [
// 递归左子树
...postorderTraversal(root.left),
// 递归右子树
...postorderTraversal(root.right),
root.val,
]
: [];
};
```