Reputation: 73
I have a pseudo- code:
function func(BST t):
x = MIN(t)
for i=1..n do:
print x.key
x = SUCCESSOR(x)
Now, I need to prove it's runnig time is THETA(n). BUT, I know SUCCESSOR running time is O(logn), and therefor running time is O(nlogn). where is my mistake here?
Thank in advance...
Upvotes: 0
Views: 189
Reputation: 66775
There are two possibilities:
O(nlogn)
O(logn)
), but you can deduce, that when performing it one after another it actually degenerates to theta(1)
. In fact, good implementation of SUCCESSOR in BST should have amortized theta(1)
complexity as each node will be visited at most twice during the whole func
execution.Upvotes: 2
Reputation: 178411
It really depends on the implementation of your BST, but if your BST holds a 'father' node, and is using it to find the successor, it will need to traverse each edge at most twice - once one you go "down", the first time to the node, and one when you go "up", back from it.
Since a tree has n-1
edges, you get at most 2*(n-1)
number edges read, and this is O(n)
.
Note that indeed the worst case of the SUCCESSOR()
function is O(logn)
, but the average case is O(1)
, if it is implemented the way I described.
Upvotes: 0