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);
}
}
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;
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.