I am practicing for a data structures exam and have been working on the question: "Write an algorithm that finds the kth highest node value in a binary search tree T. The algorithm must run in O(d), where d is the depth of the tree."
I have come up with this (after several hours) and am unsure about the runtime, I have traversed the tree twice, is this 2d and therefor just d? I was also hoping on some advice about how to reduce the number of methods I've used (if possible).
Here's my answer using a recursive helper method for counting the number of nodes in the tree and an in-order DFS:
public int getKthHighestValue(Node root, int k) {
int nodeCount = countNodes(root);
if (k < 0 || k > nodeCount)
return -1;
ArrayList<Integer> nodeList = new ArrayList<>();
getNodeValues(root, nodeList);
return nodeList.get(k-1);
}
private void getNodeValues(Node root, ArrayList<Integer> nodeList) {
if (root == null) {
return;
}
getNodeValues(root.getLeft(), nodeList);
nodeList.add(root.getValue());
getNodeValues(root.getRight(), nodeList);
}
private int countNodes(Node root) {
if (root == null) {
return 0;
}
return 1 + countNodes(root.getLeft()) + countNodes(root.getRight());
}