Reputation: 13
I need help searching a binary tree with int data(not necessarily binary search tree) and see if an element is in the tree. If it is in the tree return the reference and if it is not found return null. This is the code I have so far.
Node search(TreeNode root, int key){
if(root == null){
return null;
}
search(root.left, key);
search(root.right, key);
if(root.right.data === key || root.left.data == key){
return root;
}else{
return null;
}
}
Upvotes: 0
Views: 80
Reputation: 2768
You call search(root.left, key);
. That is great. Except that if the element you are searching for is indeed in the left branch of the current Node, nothing happens. The method keeps executing, no matter what the recursive call has reported. You need to keep that data and handle it appropriately.
Therefore you should do something like this:
Node search(TreeNode root, int key){
if (root == null)
return null;
if (root.data == key)
return root;
Node n;
n = search(root.left, key);
if (n != null)
return n;
n = search(root.right, key);
if (n != null)
return n;
return null;
}
Upvotes: 1