Re: Binary Tree Search[HELP]
Quote:
I noticed when searching for Items in the left subtree (A,B,D,H) the search function works, but for(F,C,E,G) the search doesn't work. Could Anyone please tell me how to fix this logic error?
Think hard about what the search method posted actually does. It will search (and return the result of) the left branch if that child is not null...in affect, never searching the right child of a node if the left is not null. Think about your algorithm, write it out on paper, then translate that to code. One way would be to search the left child, if the value is found return the result, otherwise search the right.
Re: Binary Tree Search[HELP]
Sorry, but this didn't really help. I understand where is my error, I just have no idea how to fix it. I tried making it look like the preorderPrint class, but it doesn't work because I have to return the found TreeNode which makes things complicated.
I tired this, but with "missing return statement" error.
Code :
public static TreeNode search(TreeNode root, String st)
{
if(root ==null)
return null;
else if(st.equals(root.getString()))
{
return root;
}
while(root.getLeft() != null)
{
return search(root.getLeft(), st);
}
while(root.getRight() != null)
{
return search(root.getRight(), st);
}
}
This also gave the same error!
Code :
public static TreeNode search(TreeNode root, String st)
{
if ( root != null )
{
if(st.equals(root.getString()))
{
return root;
}
search( root.getLeft(), st);
search( root.getRight(), st );
}
else
return null;
}
Can you please suggest a fix? I spent hours on this with no luck :confused:
Re: Binary Tree Search[HELP]
Quote:
Can you please suggest a fix?
...
Quote:
Think about your algorithm, write it out on paper, then translate that to code. One way would be to search the left child, if the value is found return the result, otherwise search the right.
Re: Binary Tree Search[HELP]
I understand what you guys are saying, its just that putting it in code is is a bit tough for me :confused:
I have to search in preorder using recursion to compare the strings, and if a match is found, I have to return its corresponding TreeNode.
This is my last try, and it still doesn't work *surprise* . I think the problem is the "return null" in the else statement in "search", but removing it creates this error --> "missing return statement"
Code :
public boolean compare(TreeNode root, String st)
{
if(st.equals(root.getString()))
{
return true;
}
else
return false;
}
public TreeNode search(TreeNode root, String st)
{
if(root==null)
{
return null;
}
else if(compare(root, st) == true)
{
return root;
}
else
{
search(root.getLeft(), st);
search(root.getRight(), st);
return null;
}
}
Please help me out guys, this is driving me crazy :(