In this tutorial, we will see preorder traversal of a binary tree with the help of recursion. Preorder traversal uses DFS(depth-first-search) approach to traverse the whole tree. In Preorder traversal, we firstly print the node and then go to left of the tree and at last we go to the right of the tree with the help of recursion whole tree is traversed.
Preorder Traversal: Root Left Right.
Let us take an example.
The Preorder Traversal of above given Binary Tree will be: 2, 5, 6, 7, 10, 20, 30
Explanation:
- If we encounter any node which is null we will return back (this will be the base condition)
- Print the node value firstly
- Then recur to the left subtree using node.left
- Then recur to the right subtree using node.right The same process gets repeated until whole tree is traversed.
Algorithm:
- if (node == null) return
- print the node.
- visit the left subtree.
- visit the right subtree.
Recursive code of Preorder Traversal is implemented below:
Output:
Preorder Traversal is: 2 5 6 7 10 20 30
Complexity Analysis:
Time Complexity: O(n), where n is number of nodes in tree. This is because, we are traversing the each node of tree at once.
Space Complexity: We have not used any extra space for storing the nodes values, so O(1) can be considered as space complexity.