If node is not found, what level should go in the binary search tree

I am trying to implement this method in my binary search tree, which should tell me the depth of the element found.

My question is that the element was not found, how should my search return the level of the tree on which it went (or was placed in).

i.e. if the node does not exist in the tree, the level of the tree in which it should be inserted should be returned. I do not want to return "0" if the element is not found in the tree, and the level at which it should have been placed.

If I searched for “7”, the method should return “3”, because this is the level at which the search stopped and where theoretically “7” will be added

Here is the code that I still have, but it keeps coming back.

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;
    }
}

: ?

:

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;
}

. SO.

+4
1

: ?

, true, , false . Java ( , , ... ugh...). - !

depthSearch, : return .

, :

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);
    }
}
+4

Source: https://habr.com/ru/post/1690203/


All Articles