Java

Implement Binary Search Tree (BST) in-order traversal (depth first) in Java3 min read

For a binary tree to be a binary search tree (BST), the data of all the nodes in the left sub-tree of the root node should be less than or equals to the data of the root. The data of all the nodes in the right subtree of the root node should be greater than the data of the root. This example shows the implementation of a binary search tree in-order traversal (depth first).

What is in-order traversal (depth first)?

Tree traversal means we visiting all nodes in the tree, visiting means either of accessing node data or processing node data. Traversal can be specified by the order of visiting 3 nodes, ie current node, left subtree and right subtree. In in-order traversal, first we visit the left subtree, then current node and then right subtree. In-order traversal gives data in the sorted order. In our current example we use recursive approach to implement in-order traversal.




Here is an example picture of binary search tree (BST) for our example code:

Here is the steps to implement in-order traversal:

  1. Start with root node.
  2. Check if the current node is empty / null.
  3. Traverse the left subtree by recursively calling the in-order function.
  4. Display the data part of the root (or current node).
  5. Traverse the right subtree by recursively calling the in-order function.

BtsNode:

BinarySearchTreeImpl:

Output:

Leave a Comment