4

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.

If I searched for "7", the method should return "3" because that is the level where the search stopped and where in theory the "7" would be added

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.

AmyF
  • 47
  • 5

1 Answers1

4

My second question is would it make sense to add the depth level counter logic to my find method?

No, this method is supposed to return true if found and false otherwise. You can't return multiple values in Java (you can create an object that will hold both but that's... ugh...). But even if you could - a method should do one thing!

As for depthSearch there is a problem with the implementation: you don't return the result from the recursive calls.

It can be easily fixed though:

public int depthSearch(Node root, int key) {

    if (root == null || root.data == key) {
        return 1;
    }    
    else if (root.data > key) {
        return 1 + depthSearch(root.left, key);
    } else {
        return 1 + depthSearch(root.right, key);
    }
}
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129