前序,中序,后续遍历的非递归写法
2019-08-18 本文已影响0人
RedLee666
一、前序遍历
function preOrder(root) {
let stack = [], res = [], p;
stack.push(root);
while (stack.length > 0) {
p = stack.pop();
if (p) {
res.push(p.val);
stack.push(p.right);
stack.push(p.left);
}
}
console.log(res.join('-'));
}
二、中序遍历
function inOrder(root) {
let stack = [], res = [], p = root;
while (p || stack.length > 0) {
while (p) {
stack.push(p);
p = p.left;
}
p = stack.pop();
res.push(p.val);
p.right ? p = p.right : p = null;
}
console.log(res.join('-'));
}
三、后序遍历
function postOrder(root) {
let stack = [], res = [], p = root;
while (p || stack.length > 0) {
while (p) {
stack.push(p);
p = p.left;
}
p = stack.pop();
res.push(p.val);
if (stack.length > 0 && p == stack[stack.length - 1].left)
p = stack[stack.length - 1].right;
else
p = null;
}
console.log(res.join('-'));
}