Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nth largest element in a binary search tree

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???

like image 804
Jony Avatar asked Apr 10 '10 05:04

Jony


People also ask

What is the largest element in a binary search tree?

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.

How do you find the kth largest element in a BST?

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.

How will you find the second largest element in a binary search tree?

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.

What is the time complexity of a binary search tree with n elements?

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).


1 Answers

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);
like image 85
Vallabh Patade Avatar answered Oct 18 '22 07:10

Vallabh Patade