문제

Consider the code :

int Tree::height(tree *node) {
    if (!node) return -1;

    return 1 + max(height(node->left), height(node->right));
}

What is the complexity of this method ? O(n) or O(log(n)) ?

I think it's O(n) , since in the worst case we'd check all the nodes , doesn't ?

Can you give an example of a better implementation ?

Thanks

도움이 되었습니까?

해결책

I think you're checking all the nodes in all cases, not just the worst case. So yes, O(N).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top