AI Features

Pre-Order Traversal

In this lesson, we will cover the traversal strategy, 'Pre-Order Traversal', in a Binary Search Tree and implement it in JavaScript.

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:

  1. Visit the currentNode, i.e., print the value stored at the node

  2. Call the preOrderPrint() function on the left subtree of the currentNode.

  3. Call the preOrderPrint() function on the right subtree of the currentNode.

Implementation in JavaScript

Here is how we will implement the preOrderPrint in JavaScript:

preOrderPrint(currentNode) {
//if the currentNode IS NOT EQUAL to null
if (currentNode!==null) {
//print its value
console.log(currentNode.val);
//make recursive call to the left subtree
this.preOrderPrint(currentNode.leftChild);
//make recursive call to the right subtree
this.preOrderPrint(currentNode.rightChild);
}
//if the currentNode IS EQUAL to null, then
//we simply return
}

Yes, it is as simple as that! ...

Ask