This tutorial provides code for implementing in-order traversal of a Binary Tree.
In-Order Traversal of Binary Tree
Binary Tree traversal is a process of visiting each node of Binary Tree exactly once. In-Order traversal falls into depth-first search as search is deepended on child nodes of a node before moving to its sibling.
In-order traversal is a special type of Tree traversal wherein left node data is printed before node data followed by right child node data. This results into recursive function calls as you can't print a node unless all of its left node data has been printed.
Let's consider below Binary Tree -
Here is the In-Order Traversal of above tree -
10 20 30 40 50 60 70 80 90
Java Implementation of In-Order Traversal of Binary Tree
Here is Java code for Binary Tree containing methods for inserting data and in-order traversal -
package com.aksain.data.structures;
public class BinaryTreeWithInOrderTraversal<T extends Comparable<T>> {
private Node root;
private class Node {
T data;
Node left;
Node right;
private Node(T data) {
this.data = data;
}
}
private Node doInsert(T data, Node node) {
if(node == null) {
return new Node(data);
}
int result = data.compareTo(node.data);
if(result < 0) {
node.left = doInsert(data, node.left);
} else if(result > 0) {
node.right = doInsert(data, node.right);
}
return node;
}
public void insert(T data) {
root = doInsert(data, root);
}
private void doInOrder(Node node) {
if(node == null) {
return;
}
doInOrder(node.left);
System.out.print(node.data + " ");
doInOrder(node.right);
}
public void inOrder() {
doInOrder(root);
System.out.println();
}
public static void main(String[] args) {
final BinaryTreeWithInOrderTraversal<Integer> binaryTree = new BinaryTreeWithInOrderTraversal<>();
binaryTree.insert(50);
binaryTree.insert(30);
binaryTree.insert(10);
binaryTree.insert(20);
binaryTree.insert(40);
binaryTree.insert(70);
binaryTree.insert(60);
binaryTree.insert(80);
binaryTree.insert(90);
binaryTree.inOrder();
}
}
Here is the output of above code -
10 20 30 40 50 60 70 80 90
Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.