前序遍历
var preorderTraversal = function(root) {
const stack = [root]
let res = []
if(!root){return []}
while(stack.length){
root = stack.pop()
res.push(root.val)
root.right && stack.push(root.right)
root.left && stack.push(root.left)
}
return res
let res= []
const qx = function(root){
if(!root){return}
res.push(root.val)
qx(root.left)
qx(root.right)
}
qx(root)
return res
};
中序遍历
var inorderTraversal = function(root) {
const stack = []
const res = []
while(stack.length || root){
if(root){
stack.push(root)
root = root.left
}else{
let o = stack.pop()
res.push(o.val)
root= o.right
}
}
return res
const res = []
const zx = function(root){
if(!root){
return
}
zx(root.left)
res.push(root.val)
zx(root.right)
}
zx(root)
return res
};
后序遍历
var postorderTraversal = function(root) {
递归思想
let res = []
const hx = function(root){
if(!root) return
hx(root.left)
hx(root.right)
res.push(root.val)
}
hx(root)
return res
let stack = [root]
let res = []
if(!root){ return []}
while(stack.length){
let a = stack.pop()
res.push(a.val)
a.left && stack.push(a.left)
a.right && stack.push(a.right)
}
return res.reverse()
};