update: 二叉树的层序遍历
This commit is contained in:
parent
f391e66174
commit
7ff3a150b7
@ -17,11 +17,11 @@ export const levelOrder = function (root) {
|
||||
const leave = queue.length // 记录这一层有几个
|
||||
for (let i = 0; i < leave; i++) { // 一次性把固定个数的队列执行完
|
||||
const node = queue.shift()
|
||||
if (node.left) queue.push(node.left)
|
||||
if (node.right) queue.push(node.right)
|
||||
tmp.push(node.val)
|
||||
if (node && node.left) queue.push(node.left)
|
||||
if (node && node.right) queue.push(node.right)
|
||||
if (node) tmp.push(node.val)
|
||||
}
|
||||
res.push(tmp)
|
||||
if (tmp.length) res.push(tmp)
|
||||
}
|
||||
|
||||
return res
|
||||
|
@ -8,4 +8,7 @@ test('二叉树的层序遍历', () => {
|
||||
[9, 20],
|
||||
[15, 7]
|
||||
])
|
||||
|
||||
const source1 = []
|
||||
expect(levelOrder(Tree.arrToTree(source1))).toEqual([])
|
||||
})
|
||||
|
Loading…
Reference in New Issue
Block a user