-
Notifications
You must be signed in to change notification settings - Fork 1
/
102.二叉树的层次遍历.js
52 lines (47 loc) · 997 Bytes
/
102.二叉树的层次遍历.js
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
43
44
45
46
47
48
49
50
51
52
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
/**
* 关键思路
* 广度优先 - 从上到下,从左到右
* 用队列存放待遍历节点
* 然后索引自增遍历队列
* 存放队列时,将深度level一并存入
*/
var levelOrder = function(root) {
if (!root) {
return []
}
const queen = [{ ...root, level: 0 }]
let num = 0
const result = []
const get = () => {
const node = queen[num]
if (node) {
if (!result[node.level]) {
result[node.level] = []
}
result[node.level].push(node.val)
if (node.left) {
queen.push({ ...node.left, level: node.level + 1 })
}
if (node.right) {
queen.push({ ...node.right, level: node.level + 1 })
}
num++
if (num <= queen.length) {
get()
}
}
}
get()
return result
};