4

I tried this, but I am getting compile time error. What I am missing ? I also have to return false if the element not found

public boolean search(Node root, Node node){
        if(root==node){
            return true;
        }
        if(root.getLeft()!=null){
            search(root.getLeft(), node);
        }

        if(root.getRight()!=null){
            search(root.getRight(), node);
        }
    }
3
  • My answer covered the compile error but you also have an algorithm error. I deleted the answer. Commented Feb 10, 2015 at 9:38
  • What happens when the node is not found? Commented Feb 10, 2015 at 9:40
  • I edited the answer to also correct the algorithm Commented Feb 10, 2015 at 9:44

2 Answers 2

4

You have a compile error because you don't always return something :

    if(root.getLeft()!=null){
        search(root.getLeft(), node);
    }

    if(root.getRight()!=null){
        search(root.getRight(), node);
    }

This would fix the compile error but not the algorithm :

    if(root.getLeft()!=null){
       return search(root.getLeft(), node);
    }

    if(root.getRight()!=null){
        return search(root.getRight(), node);
    }

This should fix the algorithm :

    if(root.getLeft()!=null && search(root.getLeft(), node)) {
      return true;
    }

    if(root.getRight()!=null && search(root.getRight(), node)){
       return true;
    }
    return false;
Sign up to request clarification or add additional context in comments.

1 Comment

what if the element not found ? i have to return false
1
public boolean search(Node root, Node node){
    if(root == node){
        return true;
    }
    boolean found = false;

    if(root.getLeft() != null ){
        found = search(root.getLeft(), node);
    }

    if(!found && root.getRight() != null )
    {
        found = search(root.getRight(), node);
    }

    return found;
}

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.