4

Suppose in a given binary tree if each node contains number of child elements, then what is the optimal way to find k'th smallest element in the tree ?

Please note this is not regular BST. Each node is containing number of child element under it.

Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79

3 Answers3

4
find_element(root, k)

    if(root.left.nchildren + 1 == k - 1) 
        return root;

    if(root.left.nchildren + 1 >= k)
        return find_element(root.left, k)             

    else 
        return find_element(root.right, k - (root.left.children + 1))
Simone
  • 2,261
  • 2
  • 19
  • 27
  • @ajeet, Simone: `each node contains number of child elements`. this includes the right subtree. if you are looking for the nth element in a full binary tree with n elements, this algorithm will wrongly return the root. – amit Sep 06 '11 at 13:20
  • @amit, Observe that Simone is counting left.nchildren not root.nchildren. And Simone is counting K starting from 0. Considering that his algo will return right result. – Ajeet Ganga Sep 06 '11 at 16:11
  • @ajeet: Simone edited the answer after I made the comment, and this issue was indeed solved by counting the left son size instead the root size. My comment is not relevant anymore – amit Sep 06 '11 at 17:05
  • @amit : Got it amit. :) Also in that case, the answer I had posted within the gap of 30second was indeed the correct one. – Ajeet Ganga Sep 07 '11 at 21:14
0

Traverse BST in InOrder traverse manner and store elements to array. Your array is a sorted array.

Community
  • 1
  • 1
Cannon
  • 2,725
  • 10
  • 45
  • 86
0

This is what I got:

find (root, k)
{
leftChildCount = root->left->n
rightChildCount = root->right->n

if (leftChildCount+1 == k)
  Print root node
else if (k< leftChildCount)
  Find(root->left,k)
else
  Find(root->right,k-leftChildCount)
}
Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79