How to implement InOrder Traversal in Binary Tree?
💻 coding

How to implement InOrder Traversal in Binary Tree?

1 min read 171 words
1 min read
ShareWhatsAppPost on X
  • 1InOrder traversal visits nodes in the order of left subtree, root, and then right subtree.
  • 2The Java implementation demonstrates creating a binary tree and performing InOrder traversal.
  • 3The output of the InOrder traversal for the given binary tree is 4, 2, 5, 1, 3.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"InOrder traversal visits nodes in the order of left subtree, root, and then right subtree."

How to implement InOrder Traversal in Binary Tree?

The Technique for traversal in an Inorder is slightly different from what we were doing in PreOrder Traversal. Here we go through left node, then data and then the right node.

In an InOrder traversal, the root is visited between the subtrees. InOrder traversal is defined as follows:

- Traverse the left subtree in InOrder.

- Visit the root.

- Traverse the right subtree in InOrder.

Java Code for above Implementation is as below:

package askgif.tree;

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
 PrintInOrderTraversal(root);

	}

	private static void PrintInOrderTraversal(Node treeNode) {
		if(treeNode == null)
			return;
		PrintInOrderTraversal(treeNode.left);
		System.out.println(treeNode.data);
		PrintInOrderTraversal(treeNode.right);
		
	}

}
4
2
5
1
3

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 9 August 2018 · 1 min read · 171 words

Part of AskGif Blog · coding

You might also like

How to implement InOrder Traversal in Binary Tree? | AskGif Blog