Skip to content

Commit

Permalink
二叉树的统一迭代法 javaScript版本
Browse files Browse the repository at this point in the history
  • Loading branch information
flames519 committed May 31, 2021
1 parent 1b39577 commit e9c91e7
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions problems/二叉树的统一迭代法.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,86 @@ func postorderTraversal(root *TreeNode) []int {
}
```

javaScript:

> 前序遍历统一迭代法
```js

// 前序遍历:中左右
// 压栈顺序:右左中

var preorderTraversal = function(root, res = []) {
const stack = [];
if (root) stack.push(root);
while(stack.length) {
const node = stack.pop();
if(!node) {
res.push(stack.pop().val);
continue;
}
if (node.right) stack.push(node.right); //
if (node.left) stack.push(node.left); //
stack.push(node); //
stack.push(null);
};
return res;
};

```

> 中序遍历统一迭代法
```js

// 中序遍历:左中右
// 压栈顺序:右中左

var inorderTraversal = function(root, res = []) {
const stack = [];
if (root) stack.push(root);
while(stack.length) {
const node = stack.pop();
if(!node) {
res.push(stack.pop().val);
continue;
}
if (node.right) stack.push(node.right); //
stack.push(node); //
stack.push(null);
if (node.left) stack.push(node.left); //
};
return res;
};

```

> 后序遍历统一迭代法
```js

// 后续遍历:左右中
// 压栈顺序:中右左

var postorderTraversal = function(root, res = []) {
const stack = [];
if (root) stack.push(root);
while(stack.length) {
const node = stack.pop();
if(!node) {
res.push(stack.pop().val);
continue;
}
stack.push(node); //
stack.push(null);
if (node.right) stack.push(node.right); //
if (node.left) stack.push(node.left); //
};
return res;
};

```



-----------------------
Expand Down

0 comments on commit e9c91e7

Please sign in to comment.