# 二叉树三种遍历的非递归思路（JAVASCRIPT)

5 篇文章 1 订阅
3 篇文章 0 订阅

## 前序遍历

第一种方法：

var preorderTraversal = function(root) {
var stack = [];
var res = [];

var p = root;
if(root == null)return [];

while(stack.length!=0 || p!=null){
//Side by side to join the array, and deposited in the stack, the future need to use these root nodes  into the right sub-tree
while(p!=null){
stack.push(p);
res.push(p.val);
p = p.left;
}
//  When p is empty, it means that both the root and the left subtree are traversed, and the right tree goes
if(stack.length!=0){
p = stack.pop();
p = p.right;
}

}

return res;
};

var preorderTraversal = function(root) {
var result = [];
var stack = [];
var p = root;
while(stack.length!=0 || p != null) {
if(p != null) {
stack.push(p);
result.push(p.val); // Add before going to children
p = p.left;
} else {
var node = stack.pop();
p = node.right;
}
}
return result;
};

## 中序遍历

var inorderTraversal = function(root) {
var stack = [];
var res = [];
var p = root;
if(root == null) return [];

while( stack.length!=0 || p!=null){

while(p!=null){
stack.push(p);
p = p.left;
}

if(stack.length!=0){
p= stack.pop();
res.push(p.val);
p = p.right;
}
}

return res;
};

var inorderTraversal = function(root) {
var result = [];
var stack = [];
var p = root;
while(stack.length!=0 || p != null) {
if(p != null) {
stack.push(p);
p = p.left;
} else {
var node = stack.pop();
result.push(node.val); // Add after all left children
p = node.right;
}
}
return result;
};

## 后序遍历

第一种方法：

var postorderTraversal = function(root) {
var Stack = [];
var result = [];

if(root==null)
return [];

Stack.push(root);
while(Stack.length!=0)
{
var node= Stack.pop();
result.push(node.val);

if(node.left)
Stack.push(node.left);

if(node.right)
Stack.push(node.right);

}
return result.reverse();

};

var postorderTraversal = function(root) {
var result = [];
var stack = [];
var p = root;
while(stack.length!=0 || p != null) {
if(p != null) {
stack.push(p);
result.unshift(p.val); // Reverse the process of preorder
p = p.right; // Reverse the process of preorder
} else {
var node = stack.pop();
p = node.left; // Reverse the process of preorder
}
}
return result;

};
05-07 1796
07-29 147
09-07 668
09-08 181
01-06 598
06-29 8万+
09-13 203
10-16 4万+
05-10 799
03-27 8101

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

©️2022 CSDN 皮肤主题：编程工作室 设计师：CSDN官方博客

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。