How to find the running time of these two functions?

I am familiar with the big O record and runtime, and most of the time I can find out the runtime of the algorithm, but I'm not sure about that. I am dealing with a tree here.

First method:

static boolean containsData(TreeNode treeRoot, String data) {
    if(treeRoot == null)
        return false;
    if(data.equals(treeRoot.data))
        return (true);
    else if((data.compareTo(treeRoot.data))<0)
        return(containsData(treeRoot.left, data));
    else
        return(containsData(treeRoot.right, data));
}

Second method:

static boolean containsData2(TreeNode treeRoot,String data){
    if (treeRoot != null) {
        if (treeRoot.data.contains(data)) {
            return true;
        } else {
            return containsData2(treeRoot.left,data) || containsData2(treeRoot.right,data); 
        }
    }
    return false;   
}

I would say that both methods are O (n). I do not see how one of them will be O (log (n)) .

+4
source share
4 answers

Both methods have the worst running time O (n) if the tree is not balanced.

The first will work in O (log n) if the tree is balanced.

- O (n) , , . , . . , O (n). O (n).

+4

, , . . @Sumeet, Big-O, , . O(lgn). n, O(n). , .

+3

O (n), , , .

O (logn), , , Red Black Trees, AVL, .

O (n) , O (n), , . , O (logn)

+2

n , O(n) ( ), . Height , O(log n), .

0

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


All Articles