How to find out the second largest largest element in a binary search tree?
If a BST have atleast 2 nodes then…
Second largest Element in a BST is the parent of Largest Element of BST.
ie its the parent of rightmost node.
If a BST don’t have right subtree Second largest element is the rightmost child of left subtree.
1 Like
void print2ndLargest ( node * root)
{
if(root==NULL||(root->Rchild==NULL&&root->Lchild==NULL))
{
cout<<"2nd Largest Not possible \n";
return;
}
if(root->Rchild==NULL)
{
node * temp;
temp=root->Lchild;
while(temp->Rchild!=NULL)
{
temp=temp->Rchild;
}
cout<<"2nd Largest : "<< temp->info;
return;
}
node * parentt;
node * temp;
parentt=root;
temp=root->Rchild;
while(temp->Rchild!=NULL)
{
parentt=temp;
temp=temp->Rchild;
}
cout<< "2nd Largest : " << parentt->info; //Largest is : temp->info
}
^ Hope this helps.
2 Likes