-
Notifications
You must be signed in to change notification settings - Fork 2
/
剑指Offer32-III.从上到下打印二叉树III.html
85 lines (75 loc) · 2.35 KB
/
剑指Offer32-III.从上到下打印二叉树III.html
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>剑指 Offer 32 - III. 从上到下打印二叉树 III</title>
</head>
<body>
<script src="../helper/tree.js"></script>
<script>
// https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/
// 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
// 3
// / \
// 9 20
// / \
// 15 7
// 返回其层次遍历结果:
// [
// [3],
// [20,9],
// [15,7]
// ]
// 提示:
// 提示:
// 节点总数 <= 1000
/**
* 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) {};
// --- answer-1 ---
// --- answer-1 ---
// 层次遍历拓展
var levelOrder = function (root) {
if (root === null) return [];
const result = [];
let stack = [root];
let nextStack = [];
let level = [];
while (stack.length) {
let node = stack.shift();
level.push(node.val);
node.left && nextStack.push(node.left);
node.right && nextStack.push(node.right);
if (stack.length === 0) {
result.length & 1 && level.reverse();
result.push(level);
stack = nextStack;
nextStack = [];
level = [];
}
}
return result;
};
// --- answer-2 ---
// --- answer-2 ---
var root = [3, 9, 20, null, null, 15, 7];
var result = [[3], [20, 9], [15, 7]];
var tree = buildTreeByArray([...root]);
console.log('tree = ', tree);
console.log('root = ', root);
console.log('result = ', result);
console.log('levelOrder = ', levelOrder(tree));
</script>
</body>
</html>