Skip to content

Commit e12ecbf

Browse files
committed
102. 二叉树的层序遍历
1 parent aad7996 commit e12ecbf

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

102. 二叉树的层序遍历.js

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number[][]}
11+
*/
12+
// 广度优先通过队列处理 【深度优先用栈】
13+
// 方法一:BFS通用模版 广度优先:迭代法 时间O(n)、空间O(n)
14+
var levelOrder = function (root) {
15+
let result = [], list = [root]
16+
while (list.length) {
17+
let len = list.length, level = [], cur
18+
while (len--) {
19+
cur = list.shift()
20+
if (cur !== null) {
21+
level.push(cur.val)
22+
cur.left !== null && list.push(cur.left)
23+
cur.right !== null && list.push(cur.right)
24+
}
25+
}
26+
level.length && result.push(level)
27+
}
28+
return result
29+
}
30+
31+
// 方法二 标记法,偏技巧
32+
var levelOrder = function (root) {
33+
if (!root) return []
34+
let result = [], level = [], list = [root, null]
35+
while (list.length > 0) {
36+
const cur = list.shift()
37+
if (cur) {
38+
level.push(cur.val)
39+
cur.left && list.push(cur.left)
40+
cur.right && list.push(cur.right)
41+
} else { // 一层已经遍历完了
42+
result.push(level)
43+
level = []
44+
list.length > 0 && list.push(null)
45+
}
46+
}
47+
return result
48+
}
49+
50+
// 方法三 递归 时间O(n),空间O(h) h为树高度
51+
var levelOrder = function (root) {
52+
if (!root) return []
53+
let result = []
54+
function dfs(cur, level) {
55+
if (cur != null) {
56+
!result[level] && (result[level] = [])
57+
result[level].push(cur.val)
58+
cur.left && dfs(cur.left, level + 1)
59+
cur.right && dfs(cur.right, level + 1)
60+
}
61+
}
62+
dfs(root, 0)
63+
return result
64+
}

0 commit comments

Comments
 (0)