- 递归法
var preorderTraversal = function(root) {
let res = []
function dfs(root){
if(!root) return
res.push(root.val)
dfs(root.left)
dfs(root.right)
}
dfs(root)
return res
}
- 迭代法
var preorderTraversal = function(root) {
if(!root) return []
let res = []
let stack = [root]
while(stack.length){
let node = stack.pop()
res.push(node.val)
node.right && stack.push(node.right)
node.left && stack.push(node.left)
}
return res
}
- 递归法
var inorderTraversal = function(root) {
let res = []
function dfs(root){
if(!root) return
dfs(root.left)
res.push(root.val)
dfs(root.right)
}
dfs(root)
return res
};
- 迭代法
var inorderTraversal = function(root) {
if(!root) return []
let stack = []
let res = []
let cur = root
while(stack.length || cur){
while(cur){
stack.push(cur)
cur = cur.left
}
let node = stack.pop()
res.push(node.val)
if(node.right){
cur = node.right
}
}
return res
};
- 递归法
var postorderTraversal = function(root) {
const res = []
function dfs(root){
if(!root) return
dfs(root.left)
dfs(root.right)
res.push(root.val)
}
dfs(root)
return res
};
- 迭代法
var postorderTraversal = function(root) {
if(!root) return []
const res = []
const stack = [root]
while(stack.length){
let node = stack.pop()
res.push(node.val)
node.left && stack.push(node.left)
node.right && stack.push(node.right)
}
return res.reverse()
};