-
Notifications
You must be signed in to change notification settings - Fork 0
/
102.二叉树的层序遍历.js
65 lines (55 loc) · 1.42 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode.cn id=102 lang=javascript
*
* [102] 二叉树的层序遍历
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
// // 广度优先
// const result = [];
// if (!root) return result;
// const nodes = [];
// nodes.push(root);
// while(nodes.length) {
// const len = nodes.length;
// result.push([]);
// // 每次循环把当前一层的取完,然后再一遍添加元素。
// for (let i = 0; i < len; i++) {
// const node = nodes.shift();
// result[result.length - 1].push(node.val);
// if (node.left) nodes.push(node.left);
// if (node.right) nodes.push(node.right);
// }
// }
// return result;
// 深度优先
const result = [];
if (!root) return result;
const dfs = (result, node, level) => {
// 新的层级创建
if (result.length - 1 < level) {
result.push([]);
}
result[level].push(node.val);
if (node.left) {
dfs(result, node.left, level + 1);
}
if (node.right) {
dfs(result, node.right, level + 1)
}
}
dfs(result, root, 0)
return result;
};
// @lc code=end