0
votes

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.

1
This is procedural code. Why was it tagged as OOP?tereško

1 Answers

1
votes

Return if self::$counter > $k.

Actually, you shouldn't get to that state.

Since your function seems intended to return a node, what you would do is return NULL if the count is smaller.

If the count is equal, you would return the current node. And if a recursion returned a non-NULL, you would immediately return that same value.