Problem: Write a method which returns the kth minimum element in a given Binary Search Tree.
Solution: Use inorder traversal.
Implementation:
//Public interface
//Actual Implementation
Complexity: O(k)
Solution: Use inorder traversal.
Implementation:
//Public interface
public int KthSmallest(int k)
{
if (this.Root == null || k <= 0)
{
return 0;
}
int result;
this.KthSmallest(this.Root, ref k, out result);
return result;
}
//Actual Implementation
private void KthSmallest(BinaryTreeNode node, ref int k, out int result)
{
if (node == null)
{
result = -1;
return;
}
this.KthSmallest(node.LeftNode, ref k, out result);
if (--k == 0)
{
result = node.Value;
}
else if (k > 0)
{
this.KthSmallest(node.RightNode, ref k, out result);
}
}
No comments:
Post a Comment