var array 17 -4 24 100 -67 33 11 20 51 -350 var root value undefined l

 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
var array = [17, -4, 24, 100, -67, 33, 11, 20, 51, -350];
var root = {
value: undefined,
left: undefined,
right: undefined,
deep: 0
}
function add(val) {
if (root.value === undefined) {
root.value = val;
return;
}
var currentNode = root;
while (true) {
if (val > currentNode.value) {
if (currentNode.right === undefined) {
currentNode.right = {
value: val,
left: undefined,
right: undefined,
deep: currentNode.deep + 1
}
return currentNode.right;
}
currentNode = currentNode.right;
} else {
if (currentNode.left === undefined) {
currentNode.left = {
value: val,
left: undefined,
right: undefined,
deep: currentNode.deep + 1
}
return currentNode.left;
}
currentNode = currentNode.left;
}
}
}
function printTree() {
var levels = [''];
var currentDeep = 0;
var queue = [root];
while (queue.length > 0) {
var currentNode = queue.shift();
if (currentNode === undefined) {
levels[currentDeep] += 'u ';
continue;
}
currentDeep = currentNode.deep;
if (!levels[currentDeep]) {
levels[currentDeep] = '';
}
levels[currentDeep] += currentNode.value + ' ';
queue.push(currentNode.left);
queue.push(currentNode.right);
}
for (var i = 0; i < levels.length; i++) {
console.log(levels[i]);
}
}
add(array[0]);
for (var i = 1; i < array.length; i++) {
add(array[i]);
}
printTree();