Understand Binary Tree Inorder Traversal Problem

Problem Name: Binary Tree Inorder Traversal
Problem Description:

Binary Tree Inorder Traversal

What is Inorder Traversal?

Inorder traversal is a Depth-First Traversal method where we visit nodes in the following order:

  1. Left subtree
  2. Root node
  3. Right subtree

This traversal results in nodes being visited in sorted order if the tree is a Binary Search Tree (BST).

Example

Consider the following binary tree: binary tree image

Steps for Inorder Traversal:

  1. Start from the root (1).
  2. Visit the left subtree (2).
  3. Visit the left subtree of (2) → (4) (no left child, so print 4).
  4. Print 2 (after visiting left subtree).
  5. Visit the right subtree of (2) → (5) (no left child, so print 5).
  6. Print 1 (after visiting left subtree).
  7. Visit the right subtree (3) (no left child, so print 3).

Inorder Traversal Output:

42513

Applications of Inorder Traversal

  • Sorting elements in a Binary Search Tree (BST).
  • Expression tree evaluation (infix notation).
  • Used in binary tree visualization tools.
Category:
  • Graphs
Programming Language:
  • Java
Reference Link:

https://drawtocode.vercel.app/problems/binary-tree-inorder-traversal

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

INPUT: graph with 1,2,3,4,5 nodes

OUTPUT: 4 2 5 1 3

public static void main(String[] args) {

Node root = new Node(1);

root.left = new Node(2);

root.right = new Node(3);

root.left.left = new Node(4);

root.left.right = new Node(5);

System.out.println("Inorder Traversal:");

inorder(root);

} // Function End

Helper Function:

static void inorder(Node root) {

if (root == null){

return;

}//If End

inorder(root.left);

System.out.print(root.value + " ");

inorder(root.right);

}function end

Utility Functions and Global variables:

static class TreeNode {

int val;

TreeNode left , right;

TreeNode(int val){

this.val = val;

this.left = this.right = null;

}

} // Class end