0%

层序遍历

题目链接:
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
解法分析:纯的层序遍历,使用 BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/

/**
*
* @param root TreeNode类
* @return int整型二维数组
*/
function levelOrder(root) {
// write code here
if (!root) {
return [];
}
const res = [], queue = [];
queue.push(root);

// 从上到下遍历每一层
while (queue.length) {
const currentLevelSize = queue.length;
res.push([]);
// 从左到右遍历该层的所有结点
for (let i = 0; i < currentLevelSize; i++) {
const node = queue.shift();
res[res.length - 1].push(node.val);

// 将下一层的结点放入队列
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}

return res;
}

module.exports = {
levelOrder : levelOrder
};

本文标题:层序遍历

文章作者:Flower-F

发布时间:2022年01月08日 - 12:43

最后更新:2022年01月19日 - 16:40

-------------本文结束,感谢您的阅读-------------

欢迎关注我的其它发布渠道