Binary Tree Inorder Traversal in Java: Explanation & Practice

Traverse tree in Left-Root-Right order

Problem summary

Given a binary tree, return the inorder traversal of its nodes' values. Implement iteratively using a stack.

Starter code

public class Main {
    public static void main(String[] args) {
        // Tree:   1
        //          \
        //           2
        //          /
        //         3
        // Inorder: Left, Root, Right
        // Print: 1 3 2
    }
}

Expected output and test cases

  • [1,null,2,3]
    1 3 2
  • [] → empty
  • [1]
    1

Hints

  1. Recursive: inorder(left), visit root, inorder(right)
  2. Iterative: use stack, go left as far as possible
  3. Pop node, add to result, then go right
  4. Repeat until stack empty and current is null

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler