I'm currently using the follow code to perform in inorder traversal of a BST. My problem is getting all calculations to stop once the kth smallest is reached.
http://codepad.viper-7.com/XMGcxz
My problem is with the following function
public function _kthSmallest($node, $k){
if($node->left != NULL){
$this->_kthSmallest($node->left, $k);
}
echo $node->data . ' ';
self::$counter++;
echo self::$counter . "<br/>";
/*
if(self::$counter >= $k){
return $node->data;
}
*/
if($node->right != NULL){
$this->_kthSmallest($node->right, $k);
}
}
If I uncomment this code I run into problems because the root node always gets printed.
/*
if(self::$counter >= $k){
return $node->data;
}
*/
Any ideas of how can stop after I reach the kth smallest? Currently the function continues through the entire BST.