How to find the Nth largest node in a BST?
Do I keep a count variable while doing In Order Traversal of a BST? Return the element when the count = N???
largestElement() will find out the largest node in the binary tree: It checks whether the root is null, which means the tree is empty. If the tree is not empty, define a variable max that will store temp's data. Find out the maximum node in the left subtree by calling largestElement() recursively.
To find Kth largest element in a Binary search tree, the simplest logic is to do reverse inorder traversal and while doing reverse inorder traversal simply keep a count of number of Nodes visited. When the count becomes equal to k, we stop the traversal and print the data.
The second largest element is second last element in inorder traversal and second element in reverse inorder traversal. We traverse given Binary Search Tree in reverse inorder and keep track of counts of nodes visited. Once the count becomes 2, we print the node.
In best case, The binary search tree is a balanced binary search tree. Height of the binary search tree becomes log(n). So, Time complexity of BST Operations = O(logn).
The idea is very simple: traverse the tree in decreasing order of the values of each node. When you reach the Nth node, print that node value. Here is the recursive code.
void printNthNode(Node* root, int N)
{
if(root == NULL)
return;
static int index = 0; //These will initialize to zero only once as its static
//For every Node go to the right of that node first.
printNthNode(root->right, N);
//Right has returned and now current node will be greatest
if(++index == N)
{
printf("%d\n", root->data);
return;
}
//And at last go to the left
printNthNode(root->left, N);
}
Edit -
As per the comments below, looks like this is one-time call function due to the static local variable. This can be solved by passing wrapper object for index
as follows:
class WrapIndex {
public: int index;
};
and method signature would change to
void printNthNode(Node* root, int N, WrapIndex wrapInd)
Now, we don't need a local static variable; instead use index
of the wrapper object. The call would look like
WrapIndex wrapInd = new WrapIndex();
wrapInd.index=0;
printNthNode(root,7,wrapInd);
wrapInd.index=0;
printNthNode(root,2,wrapInd);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With