-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree-level-order.js
84 lines (64 loc) · 1.65 KB
/
tree-level-order.js
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
var Tree = function() {
this.root = null;
}
Tree.prototype.insert = function(node, data) {
if (node == null){
node = new Node(data);
}
else if (data < node.data){
node.left = this.insert(node.left, data);
}
else{
node.right = this.insert(node.right, data);
}
return node;
}
var Node = function(data) {
this.data = data;
this.left = null;
this.right = null;
}
/* head ends */
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
// now we can read/parse input
});
function levelOrder(root) {
const queue = [root];
while(queue.length > 0) {
const node = queue.shift();
process.stdout.write(`${node.data} `);
if (!!node.left) queue.push(node.left);
if (!!node.right) queue.push(node.right);
}
}
/* tail begins */
process.stdin.resume();
process.stdin.setEncoding('ascii');
var _stdin = "";
var _stdin_array = "";
var _currentline = 0;
process.stdin.on('data', function(data) {
_stdin += data;
});
process.stdin.on('end', function() {
_stdin_array = _stdin.split("\n");
solution();
});
function readLine() {
return _stdin_array[_currentline++];
}
function solution() {
var tree = new Tree();
var n = parseInt(readLine());
var m = readLine().split(" ").map(Number);
for (var i=0; i<n; i++) {
tree.root = tree.insert(tree.root, m[i]);
}
levelOrder(tree.root);
}