Skip to content

Commit 01d6bf3

Browse files
author
Manjunath
committed
min and max in binary search tree
1 parent a2291cb commit 01d6bf3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
function minInBST(root) {
24+
if (root == null) return null;
25+
if (root.leftNode == null) return root;
26+
return minInBST(root.leftNode);
27+
}
28+
29+
function maxInBST(root) {
30+
if (root == null) return null;
31+
if (root.rightNode == null) return root;
32+
return maxInBST(root.rightNode);
33+
}
34+
35+
let tree = null;
36+
tree = insertInBST(tree, 4);
37+
tree = insertInBST(tree, 2);
38+
tree = insertInBST(tree, 3);
39+
tree = insertInBST(tree, 1);
40+
tree = insertInBST(tree, 6);
41+
tree = insertInBST(tree, 5);
42+
tree = insertInBST(tree, 7);
43+
console.log('Min In BST', minInBST(tree).data);
44+
console.log('Max In BST', maxInBST(tree).data);

0 commit comments

Comments
 (0)