File tree 1 file changed +35
-0
lines changed
src/_DataStructures_/Trees/BST/find-kth-max
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ const BST = require ( '../index' ) ;
2
+
3
+ // Inorder traversal returns a sorted array
4
+ function inOrderTraversal ( root ) {
5
+ if ( root === null ) return [ ] ;
6
+ let arr = [ ] ;
7
+ // traverse left
8
+ const left = inOrderTraversal ( root . leftChild ) ;
9
+ arr = [ ...left , root . value ] ;
10
+ const right = inOrderTraversal ( root . rightChild ) ;
11
+ return [ ...arr , ...right ] ;
12
+ }
13
+
14
+ function findKthMax ( rootNode , k ) {
15
+ const arr = inOrderTraversal ( rootNode ) ;
16
+ return arr [ arr . length - k ] ;
17
+ }
18
+
19
+ // // create a BST
20
+ // const myBST = new BST(6);
21
+
22
+ // myBST.add(2);
23
+ // myBST.add(19);
24
+ // myBST.add(14);
25
+ // myBST.add(8);
26
+ // myBST.add(5);
27
+ // myBST.add(12);
28
+ // myBST.add(33);
29
+ // myBST.add(52);
30
+ // myBST.add(1);
31
+
32
+ // // find 3rd max
33
+ // console.log(findKthMax(myBST.root, 3));
34
+
35
+ module . exports = findKthMax ;
You can’t perform that action at this time.
0 commit comments