Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of BST inorder traversal if implemented this way

Well normally if using depth-first traversal, we get O(n) time. However, if we find the minimum element first then call the successor() method n times, what time complexity will it be?

I think it may be O(n log n) because successor is O(log n) but that doesn't seem right. Can anyone offer any in-depth analysis here (probably involving some limit analysis)?

like image 406
hanlindev Avatar asked Sep 16 '12 14:09

hanlindev


People also ask

What is the time complexity of inorder traversal in BST?

Time Complexity Analysis: Hence, if a tree has n nodes, then each node is visited only once in inorder traversal and hence the complexity of the inorder traversal of the binary tree is O ( n ) O(n) O(n) .

What are the time complexity of inorder and level order transversal respectively?

6. What is the time complexity of level order traversal? Explanation: Since you have to go through all the nodes, the complexity becomes O(n).

What is the time complexity for inserting an item in a binary search tree?

for 1 insert operation, avg case is O(lgn) and worst case is O(n) . For n insert operations, avg case is O(nlgn) and worst case is O(n^2) . But usually people refer to complexity of 1 insert operation.

How do you implement inorder traversal?

The easiest way to implement the inOrder traversal algorithm in Java or any programming language is by using recursion. Since the binary tree is a recursive data structure, recursion is the natural choice for solving a tree-based problem.


1 Answers

If parent pointers are present at each node, calling the successor method n times takes O(n) time. To see this observe that each edge in the tree gets visited at most twice (once from parent to child and once from child to the parent) by all the successor calls combined. Thus the total number of edges visited by all the successor calls is at most 2n. So the running time is O(n).

Now if parent pointers are not present, in every call we have to start from the root and search for the successor element by travelling through O(log n) nodes (if the tree is balanced). So the complexity becomes O(n log n).

like image 97
krjampani Avatar answered Nov 04 '22 19:11

krjampani