This program works in ฮ (N) time. ฮ (N) does not mean that each node is visited exactly once. Remember that there is a constant factor. Thus, ฮ (N) can indeed be limited to 5 N or 10 N or even 1000 N. Thus, it does not give you an accurate count of the number of visits to a node.
The time complexity of iterative traversal of the binary search tree in order can be analyzed as follows:
Consider a tree with N nodes,
Let the execution time be denoted by a complexity function T(N) .
Let the left auxiliary tree and the right hypochondrium contain the nodes X and NX-1, respectively
Then the time complexity T(N) = T(X) + T(NX-1) + c ,
Now consider the two extreme cases of a BST ,
CASE 1: A BST , which is perfectly balanced, i.e. both sub-elements have an equal number of nodes. For example, consider the below BST,
10 / \ 5 14 / \ / \ 1 6 11 16
For such a tree, the complexity function has the form
T(N) = 2 T(โN/2โ) + c
The main theorem gives us the complexity ฮ (N) in this case.
CASE 2: Completely unbalanced BST, i.e. either the left auxiliary tree or the right auxiliary tree is empty. There for X = 0. For example, consider the BST shown below,
10 / 9 / 8 / 7
Now T(N) = T(0) + T(N-1) + c ,
T(N) = T(N-1) + c T(N) = T(N-2) + c + c T(N) = T(N-3) + c + c + c . . . T(N) = T(0) + N c
Since T (N) = K, where K is a constant,
T (N) = K + N c
Here for T (N) = ฮ (N).
Thus, the complexity is ฮ(N) for all cases.