java - Search for a string in an unsorted binary tree -


i unsure need search string stored in binary tree. have search method written don't quite understand pass it. need search string before adding tree. if found, need increase counter within node object rather adding new one. tree unsorted way.

my question how search before adding it?

system.out.println("enter string stored"); stringvalue = k.nextline(); if (thestring.isempty() == true) {     node.add(stringvalue, count); } else {     // not sure here     // how send string search method?     stringvalue.treesearch(); } 

public node treesearch(string s, treenode root){      if(root.tostring().equals(s)){          return root;     }     if(left != null){          left.treesearch(s, root.left);         if(root.tostring().equals(s)){             return root;         }     }     if(right != null){          right.treesearch(s, root.right);         if(root.tostring().equals(s)){             return root;         }     }else{           return null;             } } 

i update search method this.

 public node treesearch(string s, node root){   if(root.tostring().equals(s)){      return root;     }     if(left != null){         left.treesearch(s, root.left);        return root;     }     if(right != null){        right.treesearch(s, root.right);           return root;     }else{          return null;     } } 

there bug in the way search left , right subtrees. example:

if (left != null) {     left.treesearch(s, root.left);     if (root.tostring().equals(s)) {         return root;     } } 

so ... search left subtree, ignore result of search , compare s against root ... again.

the same pattern repeated right subtree.

(since smells "learning exercise", i'll leave figure out fix.)


having said that, if don't order elements of binary tree, pretty useless data structure. better off storing elements in list or array. (the complexity of treesearch o(n) ... searching list or array.)


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -