Computer >> Computer tutorials >  >> Programming >> Javascript

Pre-order traversal in a Javascript Tree


In this traversal method, the root node is visited first, then the left subtree and finally the right subtree.

Pre-order traversal in a Javascript Tree

We start from A, and following pre-order traversal, we first visit A itself and then move to its left subtree B. B is also traversed pre-order. The process goes on until all the nodes are visited. The output of pre-order traversal of this tree will be −

A → B → D → E → C → F → G

This is the algorithm we'll be implementing:

  • Print the node's data
  • Recursively traverse left subtree
  • Recursively traverse right subtree

Let us look at how we'd implement it in our class. 

preOrder() {
   preOrderHelper(this.root);
}

Helper function: 

Example

function preOrderHelper(root) {
   if (root !== null) {
      console.log(root.data);
      preOrderHelper(root.left);
      preOrderHelper(root.right);
   }
}

You can test this using − 

Example

let BST = new BinarySearchTree();
BST.insertRec(10);
BST.insertRec(15);
BST.insertRec(5);
BST.insertRec(50);
BST.insertRec(3);
BST.insertRec(7);
BST.insertRec(12);
BST.preOrder();

Output

This will give the output −

10
5
3
7
15
12
50