94. Binary Tree Inorder Traversal

# Medium, DFS

Solution 1: Recursive

Use help function, return nothing when satisficed stop condition. Pass result list as a parameter. Return result in main function

// Some code
class Solution {
    ArrayList<Integer> res = new ArrayList<Integer>();
    
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null)
            return res;
        
        inorderTraversal(root.left);
        res.add(root.val);
        inorderTraversal(root.right);
        return res;
    }
}

Compared to preorder traversal, traversal order is changegd to left-root-right in sub-function

Solution 2: Divide & Conquer

Divide and conquer are the same as preorder binary traversal. Combine order is changed to left-root-right. Return result when satisfied stop condition.

Solution 1 is faster than solution 2.

Solution 3: Iterative (while-loop)

Push all root until left most to the stack, then pop it and add it to res. Switch to the right subtree, then repeat the last steps. It obeys the order left -> root -> right

Last updated

Was this helpful?