Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5fde75b

Browse files
committed
kth max in BST
1 parent 46c211f commit 5fde75b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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 kthMaxInBST(root, countObj, k) {
24+
if (root == null) return null;
25+
kthMaxInBST(root.rightNode, countObj, k);
26+
countObj.count++;
27+
if (countObj.count == k) {
28+
console.log(root.data);
29+
return;
30+
}
31+
kthMaxInBST(root.leftNode, countObj, k);
32+
}
33+
34+
let tree = null;
35+
tree = insertInBST(tree, 4);
36+
tree = insertInBST(tree, 2);
37+
tree = insertInBST(tree, 3);
38+
tree = insertInBST(tree, 1);
39+
tree = insertInBST(tree, 6);
40+
tree = insertInBST(tree, 5);
41+
tree = insertInBST(tree, 7);
42+
// BST
43+
// 4
44+
// / \
45+
// 2 6
46+
// / \ / \
47+
// 1 3 5 7
48+
let countObj = { count: 0 }, k = 6;
49+
console.log(k + ' Maximum In BST is');
50+
kthMaxInBST(tree, countObj, k)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /