# 代码实现
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;
console.log("请输入二叉树数组A: ");
const a = readline().split(",").map(Number);
console.log("请输入二叉树数组B: ");
const b = readline().split(",").map(Number);
// 用队列
// var head = new TreeNode(arr[0]);
// var deque = [];
// deque.unshift(head);
// 把输入的数组转为二叉树数组存储
var arr1 = [];
var arr2 = [];
for (let i = 0; i < a.length; i++) {
arr1[i] = new TreeNode(a[i]);
}
for (let i = 0; i < b.length; i++) {
arr2[i] = new TreeNode(b[i]);
}
for (let i = 0; i <= arr1.length / 2 - 1; i++) {
if (arr1[2 * i + 1]) {
arr1[i].left = arr1[2 * i + 1];
}
if (arr1[2 * i + 2]) {
arr1[i].right = arr1[2 * i + 2];
}
}
for (let i = 0; i <= arr2.length / 2 - 1; i++) {
if (arr2[2 * i + 1]) {
arr2[i].left = arr2[2 * i + 1];
}
if (arr2[2 * i + 2]) {
arr2[i].right = arr2[2 * i + 2];
}
}
// 先序遍历输出二叉树
var preOrder = (root) => {
if (root == null) {
return;
}
console.log(root.val);
preOrder(root.left);
preOrder(root.right);
};
preOrder(arr1[0]);
preOrder(arr2[0]);
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
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