forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecursive_preorder.js
More file actions
111 lines (103 loc) · 2.58 KB
/
Copy pathrecursive_preorder.js
File metadata and controls
111 lines (103 loc) · 2.58 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
/*
In Preorder traversal , the root is visited first , then the let sub-tree in preorder
fashion, and then the right subtree in preorder fashion.The traversal is defined as
* Visit the root node R
*Traverse the left sub-tree of R in preorder
*Traverse the right sub-tree of R in preorder
*/
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
//insert function inserts a new node into the binary search tree
insert(value) {
var New = new Node(value);
if (this.root === null) {
this.root = New;
return this;
}
let curr = this.root;
let prev = null;
while (curr) {
if (value < curr.data) {
prev = curr;
curr = curr.left;
}
else if (value > curr.data) {
prev = curr;
curr = curr.right;
}
}
if (prev.data > value) {
prev.left = New;
return this;
}
else {
prev.right = New;
return this;
}
}
recursive_preorder(node) {
if (node !== null) {
console.log(node.data);
this.recursive_preorder(node.left);
this.recursive_preorder(node.right);
}
}
}
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin , output: process.stdout });
const getLine = (function () {
const getLineGen = (async function* () {
for await (const line of rl) {
yield line;
}
})();
return async () => ((await getLineGen.next()).value);
})();
const main = async()=>{
console.log("Enter the number of nodes to insert");
let n = Number(await getLine());
let b = new BinarySearchTree();
console.log("Enter the values of nodes to insert\n")
for (let i = 0; i < n; i++) {
console.log("Enter the value for node " + (i + 1));
b.insert(Number(await getLine()));
}
let root = b.root;
console.log("The preorder traversal for the binary search tree ")
b.recursive_preorder(root);
process.exit(0);
}
main();
/*
Sample I/O:
Enter the number of nodes to insert
5
Enter the values of nodes to insert
Enter the value for node 1
4
Enter the value for node 2
3
Enter the value for node 3
5
Enter the value for node 4
1
Enter the value for node 5
2
The preorder traversal for the binary search tree
4
3
1
2
5
Time complexity : O(n)
Space complexity : O(n)
*/