In-order traversal in Javascript Tree

Web DevelopmentJavascriptFront End Technology

In this traversal method, the left subtree is visited first, then the root and later the right sub-tree. We should always remember that every node may represent a subtree itself.

If a binary tree is traversed in-order, the output will produce sorted key values in an ascending order.

Sub Tree

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

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

This is the algorithm we'll be implementing −

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

Let us look at how we'd implement it in our class. Since we don't want users to pass root themselves we're again going to create a helper function outside the class.

inOrder() {
inOrderHelper(this.root);
}

Helper function −

Example

function inOrderHelper(root) {
   if (root !== null) {
      inOrderHelper(root.left);
      console.log(root.data);
      inOrderHelper(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.inOrder();

Output

This will give the output −

3
5
7
10
12
15
50

Note that the elements were printed in a sorted order. This is because since we recursively explore the left subtree recursively first, we get the smallest values first. This keeps on going till the end and we get all elements in a sorted order.

raja
Published on 28-Jun-2018 08:33:29
Advertisements