I'm trying to implement this method in my Binary Search Tree that should tell me the depth of an element that was found.
My question is if the element was not found, how should my search return the level of the tree at which it exited (or be placed at).
i.e. if the node does not exist in the tree, the level of the tree at which it should be inserted at should be returned. I do not want to return "0" if the element was not found in the tree but rather the level where it should have been placed at.
Here is the code I have so far, but it keeps returning 1.
public int depthSearch(Node root, int key){
int depthLevel = 0;
if (root==null || root.data==key){
depthLevel++;
return depthLevel;
}
if (root.data > key){
depthSearch(root.left, key);
depthLevel++;
return depthLevel;
}else{
depthSearch(root.right, key);
depthLevel++;
return depthLevel;
}
}
My second question is would it make sense to add the depth level counter logic to my find method?
Here is that method:
public boolean find(int id){
Node current = root;
while(current!=null){
if(current.data==id){
return true;
}else if(current.data>id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
Thanks in advance for taking a look at my code. I was not able to find a thread with a similar question on SO.