二叉树的中序遍历
一.中序遍历
1
/ \
2 3
/ \ \
4 5 6
主要思路:用stack记录节点顺序,cur找到左子树的叶子节点,访问后出栈用cur指向父节点,接着访问右节点
方法一:非递归实现
let inorderTraversal = function(root){
const result = []
const stack = []
let current = root
while(current || stack.length){
while(current){
stack.push(current)
current = current.left
}
current = stack.pop()
result.push(current.val)
current = current.right
}
return result
}
方法二:递归实现-最简单
let preorderTraversal = function(root){
let result = []
if(root){
preorderTraversal(root.left)
result.push(root.val)
preorderTraversal(root.right)
}
return result;
}