二叉树的中序遍历,递归以及非递归的处理
一般来说树的前中后序遍历都可以用非常简单的递归方式写出来,但是非递归方式就需要使用stack,在不同的时机压栈,出栈
递归
var inorderTraversal = function (root) {
let res = []
inorder(root, res)
return res
};
var inorder = function (root, res) {
if (!root) return
inorder(root.left, res)
res.push(root.val)
inorder(root.right, res)
}
非递归
var inorderTraversal = function (root) {
let res = []
let stack = []
let current = root
while (current || stack.length > 0) {
while (current) {
// 每个节点,走到最左侧深处
stack.push(current)
current = current.left
}
current = stack.pop()
res.push(current.val)
current = current.right
}
return res
};