
leetcode-94.png
中序遍历
递归
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.left 为空,此时进入右子树再进行压栈
current = current.right
}
return res
};