new299
new299

Reputation: 814

What is the time complexity of tree traversal?

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.

Upvotes: 21

Views: 36368

Answers (2)

Nanne
Nanne

Reputation: 64429

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.

Upvotes: 2

Uri London
Uri London

Reputation: 10797

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).

Upvotes: 25

Related Questions