-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree-level-order.ts
More file actions
111 lines (85 loc) · 2.03 KB
/
tree-level-order.ts
File metadata and controls
111 lines (85 loc) · 2.03 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict';
import { count } from 'console';
class Nozim {
public value: number;
public left?: Nozim;
public right?: Nozim;
constructor(value: number) {
this.value = value;
}
static create(value: number) {
return new Nozim(value);
}
}
class Arvere {
private root: Nozim | null = null;
public insert(value: number) {
if (this.root == null) {
this.root = Nozim.create(value);
} else {
let current = this.root;
while (true) {
if (value > current.value) {
if (current.right) {
current = current.right;
} else {
current.right = Nozim.create(value);
break;
}
}
if (value < current.value) {
if (current.left) {
current = current.left;
} else {
current.left = Nozim.create(value);
break;
}
}
}
}
}
public getTransversal() {
const nodes = [];
const queue = [this.root];
while (queue.length !== 0) {
const curr = queue.shift();
nodes.push(curr?.value);
if (curr?.left != null) {
queue.push(curr?.left);
}
if (curr?.right != null) {
queue.push(curr?.right);
}
}
return nodes;
}
}
function levelOrder(values: number[]) {
const tree = new Arvere();
values.forEach((v) => tree.insert(v));
return tree.getTransversal().join(' ');
}
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString: string = '';
let inputLines: string[] = [];
let currentLine: number = 0;
process.stdin.on('data', function (inputStdin: string): void {
inputString += inputStdin;
});
process.stdin.on('end', function (): void {
inputLines = inputString.split('\n');
inputString = '';
main();
});
function readLine(): string {
return inputLines[currentLine++];
}
function main() {
readLine();
const input: number[] = readLine()
.replace(/\s+$/g, '')
.split(' ')
.map((arrTemp) => parseInt(arrTemp, 10));
console.log(levelOrder(input));
}