前序遍历lc.144
迭代法
var preorderTraversal = function(root) {
const res =[];
const stack = [];
while (root || stack.length){
while(root){
res.push(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return res;
};
中序遍历lc.94
迭代法
const inorderTraversal = (root) => {
if(!root) return [];
const res = [];
const stack = [];
while(root || stack.length){
while(root){
stack.push(root)
root = root.left;
}
root = stack.pop();
res.push(root.val);
root = root.right;
}
return res;
};
后序遍历lc.145
迭代法
var postorderTraversal = function(root) {
const res =[];
const stack = [];
while (root || stack.length){
while(root){
stack.push(root);
res.unshift(root.val);
root = root.right;
}
root = stack.pop();
root = root.left;
}
return res;
};