zhangdizhangdi

145.二叉树的后序遍历

题目

LeetCode 简单

题目

给定一个二叉树的根节点 root ,返回 它的 后序 遍历 。

示例:
输入:root = [1,null,2,3]
输出:[3,2,1]

题解

方法:递归

递归 O(n) O(n)

ts
function postorderTraversal(root: TreeNode | null): number[] {
  let res = []
  if (root) {
    const postorder = (node: TreeNode) => {
      if (node.left) postorder(node.left)
      if (node.right) postorder(node.right)
      res.push(node.val)
    }
    postorder(root)
  }
  return res
}

const tree = new Tree([3, 9, 20, null, null, 15, 7, 14, 13])
console.log('🌰', tree)
console.log('🌰', postorderTraversal(tree.root))

方法:迭代

O(n) O(n)

ts
function postorderTraversalUserStack(root: TreeNode | null): number[] {
  let res = []
  if (root) {
    const stack = [root]
    const outputStack = []

    while (stack.length) {
      console.log('stack', JSON.stringify(stack.map(i => i.val)))
      console.log('outputStack', JSON.stringify(outputStack.map(i => i.val)))

      const n = stack.pop()
      outputStack.push(n)
      if (n.left) stack.push(n.left)
      if (n.right) stack.push(n.right)

      console.log('---')
    }

    console.log('最后 outputStack', JSON.stringify(outputStack.map(i => i.val)))

    while (outputStack.length) {
      const n = outputStack.pop()
      res.push(n.val)
    }
  }
  return res
}

const tree = new Tree([3, 9, 20, null, null, 15, 7, 14, 13])
console.log('🌰', tree)
console.log('🌰', postorderTraversalUserStack(tree.root))