Monday, November 24, 2014

find kth largest/smallest element in a binary search tree

do inorder traversal

//kth smallest
void findK(Node* p, int& k) {
  if(!p || k < 0) return;
  findK(p->left, k);
  --k;
  if(k == 0) { 
    print p->data;
    return;  
  } 
  findK(p->right, k); 
}
 
//kth largest 
void findK(Node* p, int& k) {
  if(!p || k < 0) return;
  findK(p->right, k);
  --k;
  if(k == 0) { 
    print p->data;
    return;  
  } 
  findK(p->left, k); 
} 

No comments:

Post a Comment