LC-二叉树的层次遍历

题目描述

二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:给定二叉树: [3,9,20,null,null,15,7]

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回其层次遍历结果:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

代码实现

BFS(队列 + 迭代)

原理就是 BFS 一层一层地遍历,借助队列实现。

这个题的一个小技巧就是 let len = queue.length; 这行代码锁住了当前 for 循环的次数

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
/**
* 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) {
if (!root) return [];
let result = [];
let queue = [root];
while (queue.length) {
let temp = [];
let len = queue.length;
for(let i = 0; i < len; i ++) {
let node = queue.shift();
node.left && queue.push(node.left);
node.right && queue.push(node.right);
temp.push(node.val);
}
result.push(temp);
}
return result;
};

DFS(递归)

根据 result 的长度和 depth 比较,如果 result.length === depth,就创建一个空的数组。

这里的 root.left && dfs(root.left, depth+1);root.right && dfs(root.right, depth+1); 利用了 JavaScript&& 运算符的原理。

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
/**
* 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) {
if (!root) {
return [];
}
let result = [];
function recursive(root, depth) {
if (depth === result.length) {
result[depth] = [];
}
result[depth].push(root.val);
root.left && recursive(root.left, depth + 1);
root.right && recursive(root.right, depth + 1);
}
recursive(root, 0)
return result;
};