2

I cannot figure out why this function is not working. Evertime I try to make the recursive call all I get is an IE page with a cannot display error message. I left // by the lines that is causing me the trouble. I also tried the call without the $this-> and got an error function not recognized

private function insert($key, $current)    {     
    $newnode=new Node($key); 
    $parent=$this->root;
    if($this->root==null)  {  
        $this->root=$newnode;         
        return;   
    } else {
        if($newnode->data > $parent->data) {
            $parent=$parent->rightChild;
            $this->insert($key, $parent);//if I comment this line it 
                //work, but that make the function useless
        } else {
            echo "smaller ";
        }
    }
}
6
  • 9
    Possible duplicate of stackoverflow.com/questions/6005602/… (sorry, couldn't resist) Commented May 15, 2011 at 0:07
  • 2
    Is the recursion condition ever NOT met? In other words is $newnode->data > $parent->data always true? Commented May 15, 2011 at 0:07
  • @Phil I LOL'ed enough that my 4 year old came to see what was up. Commented May 15, 2011 at 0:08
  • Please put braces around both your if and else blocks. Leaving them out leads to confusion and possibly incorrect control flow Commented May 15, 2011 at 0:09
  • can we see the rest of the code that is being covered here? Commented May 15, 2011 at 0:18

1 Answer 1

1

The error is obviously an infinite recursive loop.

This is most probably due to the fact that you never use the $current argument.

You're always comparing the $newnode->data against $this->root->data which if greater once, will always be greater.

Update

Here's how I'd change it

private function insert($key, $current = null)
{
    $newnode = new Node($key);
    $parent = null === $current ? $this->root : $current;
    if (null === $parent) {
        $this->root = $newnode;
        return;
    }
    if ($newnode->data > $parent->data) {
        // same as before from here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.