forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKthLargestOnline.java
95 lines (83 loc) · 1.53 KB
/
KthLargestOnline.java
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
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/03/find-kth-smallest-element-in-binary.html
*/
package com.dsalgo;
public class KthLargestOnline
{
public static void main(String[] args)
{
BST bst = new BST();
int[] arr =
{ 12, 4, 5, 6, 2, 7, 8, 11, 2, 3 };
for (int num : arr)
bst.add(num);
System.out.println(bst.getOrdered(4));
arr = new int[]
{ 12, 1, 9, 14, 25 };
for (int num : arr)
bst.add(num);
System.out.println(bst.getOrdered(6));
}
private static class BST
{
Node root;
public void add(int num)
{
if (root == null)
{
root = new Node(num);
} else
add(root, num);
}
private void add(Node root, int num)
{
Node node = new Node(num);
if (node.value < root.value)
{
root.leftWeight++;
if (root.left == null)
root.left = node;
else
add(root.left, num);
} else
{
if (root.right == null)
root.right = node;
else
add(root.right, num);
}
}
public int getOrdered(int k)
{
return getOrdered(root, k);
}
private Integer getOrdered(Node root, int k)
{
if (root == null)
return null;
if (root.leftWeight > k)
{
return getOrdered(root.left, k);
} else if (root.leftWeight < k)
{
return getOrdered(root.right, k - root.leftWeight);
} else
{
return root.value;
}
}
}
private static class Node
{
int value;
int leftWeight;
Node left;
Node right;
public Node(int value)
{
this.value = value;
this.leftWeight = 1;
}
}
}