1、先序遍历(先根节点后左右)
function preOrder(root){
let res=[],stack=[root];
while(stack.length>0){
let node=stack.pop();
res.push(node.val);
// 因为stack栈先进后出,先左后右,所以先push右节点在push左节点
if(node.right){
stack.push(node.right);
}
if(node.left){
stack.push(node.left);
}
}
return res;
}
2、中序遍历 (左中右)
function miOrder(root){
let res=[],
stack=[];
while(root||stack.length>0){
// 先从根节点往下遍历找到最左下节点,再往上返回根节点,所以用先进后出的stack栈
while(root){
stack.push(root);
root=root.left;
}
root=stack.pop();
res.push(root.val);
root=root.right;
}
return res;
}
3、后序遍历 (左右中)
function lastOrder(root){
let res=[],
stack=[root];
while(stack.length>0){
let node=stack.pop();
// 根节点最后
res.unshift(node.val);
if(node.left){
stack.push(node.left);
}
if(node.right){
stack.push(node.right);
}
}
return res;
}
}