I/P:
24
10 20 50 -1 60 -1 -1 30 70 -1 80 110 -1 120 -1 -1 90 -1 -1 40 100 -1 -1 -1
3
O/P: 100
We will find k-th times, floor
package pep.Day31;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
public class Kth_Largest_Element_In_Tree {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
public static Node construct(int[] arr) {
Node root = null;
Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
return root;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}
int k = Integer.parseInt(br.readLine());
Node root = construct(arr);
int value = kthLargest(root, k);
System.out.println(value);
}
static int floor;
private static int kthLargest(Node root, int k) {
floor = Integer.MIN_VALUE;
int factor = Integer.MAX_VALUE;
for (int i = 0; i < k; i++) {
calculateFloor(root, factor); // will give me floor of my factor
factor = floor;
floor = Integer.MIN_VALUE;
}
return factor;
}
private static void calculateFloor(Node node, int data) {
if (node.data < data) {
int potentialFloor = node.data;
floor = Math.max(floor, potentialFloor);
}
for (Node child : node.children) {
calculateFloor(child, data);
}
}
}Time Complexity:
This approach is a naive algorithm. We are traversing the entire tree k times, by calling ceilAndFloor() for k times. Hence the total time complexity will be O(n * k) where n = number of nodes in the tree.
Space Complexity:
We are not using any auxiliary data structure, hence O(1) extra space is used. However, since we are using recursion, the recursion call stack may have O(d) space where d = maximum depth of the tree.
No comments:
Post a Comment