How do you find the kth smallest number in a binary search tree.
Respostas da entrevista
Sigiloso
31 de mai. de 2014
Inorder traversal the tree, the returned array is sorted, then find the Kth smallest number. O(n)time and O(n)space.Anyone has better idea?
3
Sigiloso
9 de jun. de 2014
Inorder traversal, but count the number of the nodes you visted, because the visiting order will just be increasing,so O(lgn) time to find the smallest node and O(1) space to store counter.
3
Sigiloso
14 de nov. de 2014
int k = 0;
node* kthLastNodeBST(node *root)
{
if (root == NULL)
return NULL;
node *temp = kthLastNodeBST(root->left);
if(temp) return temp;
k--;
if(kright);
if(temp) return temp;
return NULL;
}
k =3;
node *temp = kthLastNodeBST(root);
Sigiloso
11 de jan. de 2015
Add an integer variable to the Tree Node - numNodesLeft to keep a count of number of nodes in the left subtree of current node. This is O(lg(n))
public KBSTNode kthSmallest(KBSTNode root, int k) {
if(root==null || k=k) {
return kthSmallest(root.left,k);
}
return kthSmallest(root.right,k-root.numNodesLeft-1);
}
Sigiloso
29 de mai. de 2014
A brute force approach would be to put all the left children in an array and then look for kth element of this array.