Consider the following balanced binary tree for n=7
(this is in fact a complete binary search tree, but lets leave that out of this discussion, as a complete binary search tree is also a balanced binary search tree).
5 depth 1 (root)
/----+----\
2 6 depth 2
/--+--\ /--+--\
1 3 4 7 depth 3
For searching of any number in this tree, the worst case scenario is that we reach the maximum depth of the tree (e.g., 3 in this case), until we terminate the search. At depth 3, we have performed 3 comparisons, hence, at arbitrary depth l
, we would have performed l
comparisons.
Now, for a complete binary search tree as the one above, of arbitrary size, we can hold 1 + 2^(maxDepth-1)
different numbers. Now, let's say we have a complete binary search tree with exactly n
(distinct) numbers. Then the following holds
n = 1 + 2^(maxDepth-1) (+)
Hence
(+) <=> 2^(maxDepth-1) = n - 1
<=> log2(2^(maxDepth - 1)) = log2(n - 1)
<=> maxDepth - 1 = log2(n - 1)
=> maxDepth = log2(n - 1) + 1
Recall from above that maxDepth
told us the worst case number of comparisons for us to find a number (or it's non-existance) in our complete binary tree. Hence
worst case scenario, n nodes : log2(n-1) + 1
For studying asymptotic or limiting behaviour of this search, n
can be considered sufficiently large, and hence log2(n) ~= log2(n-1)
holds, and subsequently, we can say that a quite good (tight) upper bound for the algorithm is O(log2(n))
. Hence
The time complexity for searching in a complete binary tree,
for n
nodes, is O(log2(n))
For a non-complete binary search tree, an analogous reasoning as the one above leads to the same time complexity. Note that for a non-balanced search tree the worst case scenario for n
nodes is n
comparisons.
Answer: From above, it's clear that O(n/2)
is not a proper bound for the time complexity of a binary search tree of size n
; whereas however O(log2(n))
is. (Note that the prior might be a correct bound for sufficiently large n
, but not a very good/tight one!)