Skip to content

Latest commit

 

History

History
94 lines (79 loc) · 2.36 KB

102.二叉树的层序遍历.md

File metadata and controls

94 lines (79 loc) · 2.36 KB

102.二叉树的层序遍历

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

// @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)
 *     }
 * }
 */

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

解法 1: 递归

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

广度优先

function levelOrder(root: TreeNode | null, res: number[][] = [], children = [root]): number[][] {
  const values: number[] = []
  const tmp = children
  children = []
  for (const child of tmp) {
    if (!child) continue

    values.push(child.val)
    children.push(...[child.left, child.right])
  }
  if (children.length > 0) {
    res.push(values)
    levelOrder(root, res, children)
  }

  return res
}

解法 2: 迭代

  • 时间复杂度: O(n)
  • 空间复杂度: O(logn)
function levelOrder(root: TreeNode | null): number[][] {
  const res: number[][] = []
  let nodes: (TreeNode | null)[] = [root]
  while (nodes.length) {
    const tmp: (TreeNode | null)[] = []
    const tmpRes: number[] = []
    for (const node of nodes) {
      if (node) {
        tmpRes.push(node.val)
        tmp.push(...[node.left, node.right].filter(Boolean))
      }
    }
    if (tmpRes.length > 0) res.push(tmpRes)

    nodes = tmp
  }
  return res
}

Case

test.each([
  {
    input: { root: [3, 9, 20, null, null, 15, 7] },
    output: [[3], [9, 20], [15, 7]],
  },
])('input: root = $input.root', ({ input: { root }, output }) => {
  const rootNode = BinaryTree.deserialize(root)
  expect(levelOrder(rootNode)).toIncludeSameMembers(output)
})