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