Pre-Order Traversal
Understand pre-order traversal by exploring how to visit nodes in a binary tree in root-left-right order. Learn its implementation in C++, including recursive function calls and time complexity. This lesson helps build a foundation for other tree traversal methods.
We'll cover the following...
Introduction
In this traversal, the elements are traversed in the root-left-right order. We first visit the root/parent node, then the left child, and then the right child. Here is a high-level description of the algorithm for Pre-Order traversal, starting from the root node:
-
Visit the current node, i.e., print the value stored at the node
-
Call the
preOrderPrint()function on the left sub-tree of thecurrent node. -
Call the
preOrderPrint()function on the right sub-tree of thecurrent node.
Implementation in C++
Yes, it is as simple as that!
Explanation
First, we create an object of the BinarySearchTree class and insert some values into it. We will then pass the tree’s root to the preOrderPrint() function. If the given node is not NULL, this function prints the value at the node and calls preOrderPrint() on the left child first and then on the right child.
If you run the code for the BST given above, it will print out the following output:
Time Complexity
This is a linear-time algorithm, i.e., the time complexity of it is in because a total of recursive calls occur.
If you have understood Pre-Order Traversal clearly, it will be a piece of cake for you to understand the rest of the traversals as all three of them are similar to one another.