1st Method:
int FindKth(struct node* node,int k)
{
int countLeft;
countLeft=size(node->left);
if(countLeft+1==k)
return node->data;
else if(countLeft+1>k)
return FindKth(node->left,k);
else
return FindKth(node->right,k-countLeft-1);
}
//function to find the size of the binary tree.
int size(struct node* node)
{
if(node==null)
return 0;
else
return 1+size(node->left)+size(node->right);
}
2nd Method:
//different approach using inorder traversal and static variable
int FindKth(struct node* node,int k)
{
static int i=0;
if(node!=null)
{
FindKth(node->left,k);
i++;
if(i==k)
return node->data;
FindKth(node->right,k);
}
}
1 comment:
this will return kth smallest node,not the largest.
Post a Comment