add: 二叉树的层序遍历

This commit is contained in:
yi-ge 2020-05-13 13:55:12 +08:00
parent 36b0434402
commit f1564fe56d
3 changed files with 44 additions and 0 deletions

View File

@ -353,6 +353,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 572. 另一个树的子树 <https://leetcode-cn.com/problems/subtree-of-another-tree/>
- LintCode 1165. 另一个树的子树 <https://www.lintcode.com/problem/subtree-of-another-tree/description>
- [二叉树的层序遍历](src/tree/binary-tree-right-side-view.js)
- LeetCode 102. 二叉树的层序遍历 <https://leetcode-cn.com/problems/binary-tree-level-order-traversal/>
- LintCode 69. 二叉树的层次遍历 <https://www.lintcode.com/problem/binary-tree-level-order-traversal/description>
## 链表
- [合并K个排序链表](src/list/merge-k-sorted-lists.js)

View File

@ -0,0 +1,28 @@
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
export const levelOrder = function (root) {
const res = []
const queue = [root]
while (queue.length) { // BFS
const tmp = []
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)
}
res.push(tmp)
}
return res
}

View File

@ -0,0 +1,11 @@
import { levelOrder } from '../../src/tree/binary-tree-level-order-traversal'
import Tree from './Tree.js'
test('二叉树的层序遍历', () => {
const source = [3, 9, 20, null, null, 15, 7]
expect(levelOrder(Tree.arrToTree(source))).toEqual([
[3],
[9, 20],
[15, 7]
])
})