![]() |
VOOZH | about |
A binary tree is a non-linear hierarchical data structure where each node has at most two children which are referred to as the left child and the right child. As it has non-linear structure it can be traversed in multiple ways one such way is pre-order traversal which is a technique in which nodes are recursively visited in the order: left child, root, right child.
In this article, we will learn how to implement preorder binary tree traversal in C++, its algorithm and analyze its space and time complexity.
is a traversal technique used to visit all the nodes in a specific sequence of the . This process involves visiting the root node first, then the left subtree, and finally the right subtree.
- Visit the root node.
- Recursively perform a preorder traversal of the left subtree.
- Recursively perform a preorder traversal of the right subtree.
Consider the following example:
For preorder traversal of the above binary tree:
- Start with the root node, which is 1.
- Move to the left child, which is 2.
- Visit the left child of 2, which is 4.
- Move back to 2 and visit its right child, which is 5.
- Move back to the root node and visit the right child, which is 3.
So, the preorder traversal of the tree is: 1, 2, 4, 5, 3.
Below is the algorithm for the preorder binary tree traversal:
preorder(TreeNode* root) {
if (root == NULL)
return;
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
The following program demonstrates how we can implement the Preorder traversal in a binary tree in C++.
Preorder traversal of the binary tree is: 1 2 4 5 3 6 7
Time Complexity: O(N) where N is the total number of nodes as it traverses all the nodes at least once.
Auxiliary Space:
Following are some common applications of the preorder traversal:
You can also go through these articles to improve your knowledge about the binary tree and it's traversals: