recategorized by
606 views
1 votes
1 votes

What is the complexity of inorder traversal for a binary search tree with n nodes? 

  1. O(log n) whether the tree is balanced or unbalanced.
  2. O(log n) if the tree is balanced, O(n) otherwise.
  3. O(n) whether the tree is balanced or unbalanced.
  4. O(n) if the tree is balanced, O(n log n) otherwise.
recategorized by

1 Answer

2 votes
2 votes

The correct answer is C, O(n) whether the tree is balanced or unbalanced.

The logical reasoning behind in inorder traversal is that for each node you

  1. traverse the left sub-tree of the current node
  2. print/traverse the current node and
  3. traverse the right sub-tree of the current node.

In any case, balanced or unbalanced you essentially only visit all the nodes once. Since you are visiting all the nodes the time complexity will be equal to the number of nodes, i.e. n.

 

Additional context: In the case of search in a binary search tree time taken to search a node would be O(log n) if the tree is balanced, O(n) otherwise. 

Related questions

2 votes
2 votes
1 answer
1
rsansiya111 asked Dec 8, 2021
878 views
Suppose we do merge sort with a three-way split: divide the array into 3 equal parts, sort each part and do a 3 way merge.What would the worst-case complexity of this ver...
0 votes
0 votes
3 answers
3