/*
* @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
广度优先
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
}
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
}
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)
})