Skip to content

Latest commit

 

History

History
113 lines (96 loc) · 2.93 KB

144.二叉树的前序遍历.md

File metadata and controls

113 lines (96 loc) · 2.93 KB

144.二叉树的前序遍历

/*
 * @lc app=leetcode.cn id=144 lang=typescript
 *
 * [144] 二叉树的前序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

interface TreeNode {
  val: number
  left: TreeNode | null
  right: TreeNode | null
}

function preorderTraversal(root: TreeNode | null): number[] {}
// @lc code=end

解法 1: 递归

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
function preorderTraversal(root: TreeNode | null): number[] {
  if (!root) return []
  return [root.val].concat(preorderTraversal(root.left)).concat(preorderTraversal(root.right))
}

解法 2: 迭代

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
function preorderTraversal(root: TreeNode | null): number[] {
  const stack: Array<TreeNode> = [],
    nums: Array<number> = []
  while (root || stack.length) {
    if (root) {
      nums.push(root.val)
      stack.push(root)
      root = root.left
    } else {
      root = stack.pop()!.right
    }
  }
  return nums
}

解法 3: Morris 遍历

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
function preorderTraversal(root: TreeNode | null): number[] {
  const nums: Array<number> = []

  while (root) {
    if (!root.left) {
      nums.push(root.val)
      root = root.right
    } else {
      let pre = root.left
      while (pre.right !== null && pre.right !== root) {
        pre = pre.right
      }
      if (pre.right === null) {
        nums.push(root.val)
        pre.right = root
        root = root.left
      } else {
        pre.right = null
        root = root.right
      }
    }
  }

  return nums
}

Case

test.each([
  { input: { root: [1, null, 2, 3] }, output: [1, 2, 3] },
  { input: { root: [] }, output: [] },
  { input: { root: [1] }, output: [1] },
  { input: { root: [1, null, 2] }, output: [1, 2] },
])('input: root = $input.root', ({ input: { root }, output }) => {
  expect(preorderTraversal(BinaryTree.deserialize(root))).toEqual(output)
})