-
Notifications
You must be signed in to change notification settings - Fork 0
/
层级遍历二叉树.js
66 lines (62 loc) · 1.58 KB
/
层级遍历二叉树.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 给定一颗二叉树,按照节点层次返回一个二维数组
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
// 思路
// 使用BFS,结合depth来填充数组
var levelOrderBottom = function(root) {
var bottumUpTraversal = [];
var queue = [{ node: root, depth: 0 }];
while (queue.length != 0) {
var current = queue.shift();
if (current && current.node) {
var currentDepth = current.depth;
var currentNode = current.node;
if (bottumUpTraversal[currentDepth]) {
bottumUpTraversal[currentDepth].push(currentNode.val);
} else {
bottumUpTraversal[currentDepth] = [currentNode.val];
}
if (currentNode.left) {
queue.push({ node: currentNode.left, depth: currentDepth + 1 });
}
if (currentNode.right) {
queue.push({ node: currentNode.right, depth: currentDepth + 1 });
}
}
}
return bottumUpTraversal.reverse();
};
// 思路2
var levelOrderBottom = function(root) {
if(!root) {
return []
}
let queue = []
let result = []
queue.push(root)
while (queue.length > 0) {
let len = queue.length
let temp = []
for(let i = 0; i < len; i++) {
let node = queue.shift()
temp.push(node.val)
if (node.left != null) {
queue.push(node.left)
}
if (node.right != null) {
queue.push(node.right)
}
}
result.push(temp)
}
return result.reverse()
}