Skip to content

Commit a2291cb

Browse files
author
Manjunath
committed
insertion in BST
1 parent cf04c80 commit a2291cb

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
function insertInBST(root, data) {
10+
if (root == null) return new Node(data);
11+
else if (root.data > data) root.leftNode = insertInBST(root.leftNode, data);
12+
else root.rightNode = insertInBST(root.rightNode, data);
13+
return root;
14+
}
15+
16+
function inorderDisplay(root) {
17+
if (root == null) return;
18+
inorderDisplay(root.leftNode);
19+
console.log(root.data);
20+
inorderDisplay(root.rightNode);
21+
}
22+
23+
let tree = null;
24+
tree = insertInBST(tree, 4);
25+
tree = insertInBST(tree, 2);
26+
tree = insertInBST(tree, 3);
27+
tree = insertInBST(tree, 1);
28+
tree = insertInBST(tree, 6);
29+
tree = insertInBST(tree, 5);
30+
tree = insertInBST(tree, 7);
31+
inorderDisplay(tree);

0 commit comments

Comments
 (0)