java - Breadth-first tree -


i seem having issues structuring breadth-first tree.

in code below, have node inserted through loop in class.

the structure of tree supposed so:

       / \   b   c  /\   /\ d e  f  g 

now code:

my code structures left side correctly, whereas right side adds left side well. understand in code happens, there way prevent happening?

public node familytree;  public void breadthfirst(node newnode){     familytree = breadthfirst(familytree,newnode);  }  public node breadthfirst(node t, node newnode){     if(t == null){         t = newnode;         return t;                 }     if(t.left == null){         newnode.height = t.height + 1;                     t.left = newnode;         return t;     }     else if(t.right == null){         newnode.height = t.height + 1;             t.right = newnode;         return t;     }     else{                      t.left = breadthfirst(t.left, newnode);          t.right = breadthfirst(t.right, newnode); <-- corporate                }     return t;  } 

if using recursive, implementation "depth-first-search", breadth-first-search, use queue or fifo data structure

pseudo-code

public node breadthfirst(node t, node searchnode){   queue queue = new queue();   queue.queue(t);    while (!queue.isempty()) {     node curnode = queue.dequeue();     if (curnode == null) continue;      if (curnode.value().equals(searchnode.value()) {       return curnode;     }      queue.queue(curnode.left);     queue.queue(curnode.right);   }     return null; //or throw exception not found } 

Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -