Pre-Order Traversal
Explore how to perform pre-order traversal on binary trees, visiting nodes in root-left-right order. Understand the JavaScript implementation within a BinarySearchTree class and grasp its linear time complexity to prepare for coding interviews.
We'll cover the following...
Introduction
In pre-order traversal, the current node will be visited before its children nodes. Therefore, it is called the pre-order traversal.
The root of the tree will always be the first one to be visited.
In pre-order traversal, the elements are traversed in “root-left-right” order.
Here is a high-level description of the algorithm for Pre-Order traversal, starting from the root node:
-
Visit the
currentNode, i.e., print the value stored at the node -
Call the
preOrderPrint()function on the left subtree of thecurrentNode. -
Call the
preOrderPrint()function on the right subtree of thecurrentNode.
Implementation in JavaScript
Here is how we will implement the preOrderPrint in JavaScript:
Yes, it is as simple as that!
Putting it in the BinarySearchTree Class
Explanation
First, we create an object named BST of the BinarySearchTree class and insert some values into it. We will then pass BST.root(line 56) to the preOrderPrint() function.
If the node passed into the function is not null, this function prints the value at the node and calls preOrderPrint() on the left child first, i.e., the left subtree and then on the right child, i.e., the right subtree.
The recursive call to the rightChild only takes place once all the subsequent calls to the left subtree have been executed.
When the recursive calls will hit the null nodes, they will return from the function without doing anything.
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 preOrderPrint() 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. You can also now check your insert function as you are able to print the tree.