Binary Tree Inorder Traversal

Given a binary tree, return the_inorder_traversal of its nodes' values.

Example:

Input:
 [1,null,2,3]
   1
    \
     2
    /
   3


Output:
 [1,3,2]

Follow up:Recursive solution is trivial, could you do it iteratively?

Analysis

Approach 1 - Recursive

Following the definition of inorder traversal: left - root - right

Solution

Recursive

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        recursiveInorderTravesal(root, result);
        return result;
    }
    void recursiveInorderTravesal(TreeNode root, List<Integer> result) {
        if (root != null) {
            if (root.left != null) {
                recursiveInorderTravesal(root.left, result);
            }
            result.add(root.val);
            if (root.right != null) {
                recursiveInorderTravesal(root.right, result);
            }
        }
    }
}

TIme complexity: O(n)

Space Complexity: worst case O(n), average O(log(n))

Iterative (Using Stack)

LeetCode Official Solution In-order Traversal

public class Solution {
    public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        Stack < TreeNode > stack = new Stack < > ();
        TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            res.add(curr.val);
            curr = curr.right;
        }
        return res;
    }
}

Another Stack Implementation

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            p = p.left;
        } else {
            TreeNode node = stack.pop();
            result.add(node.val);  // Add after all left children
            p = node.right;   
        }
    }
    return result;
}

Last updated