Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexities of binary tree traversals

What is the time complexity of inorder,postorder and preorder traversal of binary trees in data structures?? Is it O(n) or O(log n) or O(n^2)??

like image 731
Mishthi Avatar asked Dec 28 '10 15:12

Mishthi


People also ask

What is time complexity of binary tree traversal?

Searching: For searching element 1, we have to traverse all elements (in order 3, 2, 1). Therefore, searching in binary search tree has worst case complexity of O(n). In general, time complexity is O(h) where h is height of BST.

What are the traversals in binary tree?

Often we wish to process a binary tree by “visiting” each of its nodes, each time performing a specific action such as printing the contents of the node. Any process for visiting all of the nodes in some order is called a traversal.

What is the complexity of post-order traversal?

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

How many traversals are in a binary tree?

On the other hand, binary trees can be traversed in multiple ways. These notes describe four different traversals: preorder, inorder, postorder, and level order.


2 Answers

In-order, Pre-order, and Post-order traversals are Depth-First traversals.

For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.

Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).

Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.

The complexity then becomes O(n + n-1), which is O(n).

like image 64
Vig Avatar answered Oct 17 '22 04:10

Vig


O(n), because you traverse each node once. Or rather - the amount of work you do for each node is constant (does not depend on the rest of the nodes).

like image 24
Vilx- Avatar answered Oct 17 '22 03:10

Vilx-