二叉树的前序、中序、后序遍历,分别给出递归与迭代写法。
递归(结构清晰):
function preorder(root, out = []) {
if (!root) return out
out.push(root.val) // 前:根左右
preorder(root.left, out)
preorder(root.right, out)
return out
}
// 中序:左根右;后序:左右根(调整三行顺序即可)迭代(用栈模拟):以前序为例,先压右再压左,保证出栈顺序为根→左→右。
function preorderIter(root) {
if (!root) return []
const stack = [root], out = []
while (stack.length) {
const n = stack.pop()
out.push(n.val)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
return out
}- 递归空间
O(h)(h 为树高),最坏O(n) - 中序遍历 + BST 可得升序序列,常用于「验证 BST / 第 K 小」