java - Searching in Pre Order Traversal way -


i have binary search tree. know how search using search property. task search tree without using search property.(say, search in binary tree) how have search.

1. if find value in current node return it.

2. else search in right. if not found in right, search in left

3. if not found in whole tree return null.

this tried.

public node search(int val) {     node target = this;     if(target.getval() == val)         return this;     else if(target.getright() == null && target.getleft() == null)         return null;     if(target.getright() != null)     {         return target.getright().search(id);     }     if(target.getleft() != null)     {         return target.getleft().search(id);     }     return null; } 

problem code is, if right child exists , val not found in right i'm getting null value. (not searching in left). how resolve this?

public node search(int val) {     node target = this;     if(target.getval() == val)         return this;     else if(target.getright() == null && target.getleft() == null)         return null;     if(target.getright() != null)     {         return target.getright().search(id); //here lies problem     }     if(target.getleft() != null)     {         return target.getleft().search(id);    } return null; 

}

the problem in code returning result of search in right subtree of node being searched.

here's updated code

public node search(int val) {     node target = null;     if(this.getval() == val)     {         return this;     }     else if(this.getright() == null && this.getleft() == null)         return target;     if(this.getright() != null)     {         target = this.getright().search(id);     }     if(target==null && this.getleft() != null)     {         target = this.getleft().search(id);    }    return target; 

}


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -