二叉树的前序、中序、后序遍历,分别给出递归与迭代写法。

递归(结构清晰):

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
}

同分类其他题目