Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of tree traversal?

Tags:

What is the time complexity of tree traversal, I'm sure it must be obvious but my poor brain can not work it out right now.

like image 869
new299 Avatar asked Feb 10 '11 11:02

new299


People also ask

What is the time complexity of Post-order transversal?

Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space.

Which is the fastest tree traversal?

c# - Fastest tree traversal - Stack Overflow.

What are the time complexity of inorder and level order traversal 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).


2 Answers

It depends what kind of traversal you are performing and the algorithm, but typically it would be O(n) where n is the total number of nodes in the tree. The canonical recursive implementation of depth first traversal, will consume memory (on the stack) in the order of the deepest level, which on a balanced tree it would be log(n).

like image 184
Uri Avatar answered Sep 24 '22 18:09

Uri


Wouldn't that just be n for a tree with n nodes?

You visit each tree-leave once, don't you? So i'd say it is linear.

like image 28
Nanne Avatar answered Sep 24 '22 18:09

Nanne