KatInterview

94. Binary Tree Inorder Traversal

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to perform an "inorder traversal" on a given binary tree and return a list of the node values in the order they are visited. An inorder traversal for any node follows a specific sequence: first, traverse its entire left subtree, then visit the node itself, and finally, traverse its entire right subtree. This definition is applied recursively throughout the tree.

Solution

Binary Tree Inorder Traversal in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        result = []
        stack = []
        current = root

        # Loop as long as there are nodes to process or nodes in the stack.
        while current or stack:
            # Traverse to the leftmost node of the current subtree.
            # Push all nodes encountered on the way onto the stack.
            while current:
                stack.append(current)
                current = current.left
            
            # At this point, `current` is None, and the stack top is the leftmost node.
            # Pop the node from the stack.
            current = stack.pop()
            
            # Add the node's value to the result.
            result.append(current.val)
            
            # Now, process the right subtree of the popped node.
            current = current.right
            
        return result

Binary Tree Inorder Traversal in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;

        // Loop as long as there are nodes to process or nodes in the stack.
        while (current != null || !stack.isEmpty()) {
            // Traverse to the leftmost node of the current subtree.
            // Push all nodes encountered on the way onto the stack.
            while (current != null) {
                stack.push(current);
                current = current.left;
            }
            
            // At this point, `current` is null, and the stack top is the leftmost node.
            // Pop the node from the stack.
            current = stack.pop();

            // Add the node's value to the result.
            result.add(current.val);

            // Now, process the right subtree of the popped node.
            current = current.right;
        }

        return result;
    }
}

Binary Tree Inorder Traversal in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> s;
        TreeNode* current = root;

        // Loop as long as there are nodes to process or nodes in the stack.
        while (current != nullptr || !s.empty()) {
            // Traverse to the leftmost node of the current subtree.
            // Push all nodes encountered on the way onto the stack.
            while (current != nullptr) {
                s.push(current);
                current = current->left;
            }

            // At this point, `current` is null, and the stack top is the leftmost node.
            // Pop the node from the stack.
            current = s.top();
            s.pop();

            // Add the node's value to the result.
            result.push_back(current->val);

            // Now, process the right subtree of the popped node.
            current = current->right;
        }

        return result;
    }
};

Binary Tree Inorder Traversal in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function inorderTraversal(root: TreeNode | null): number[] {
    const result: number[] = [];
    const stack: TreeNode[] = [];
    let current: TreeNode | null = root;

    // Loop as long as there are nodes to process or nodes in the stack.
    while (current !== null || stack.length > 0) {
        // Traverse to the leftmost node of the current subtree.
        // Push all nodes encountered on the way onto the stack.
        while (current !== null) {
            stack.push(current);
            current = current.left;
        }

        // At this point, `current` is null, and the stack top is the leftmost node.
        // Pop the node from the stack.
        // The non-null assertion `!` is safe because of the loop condition (stack.length > 0).
        current = stack.pop()!;

        // Add the node's value to the result.
        result.push(current.val);

        // Now, process the right subtree of the popped node.
        current = current.right;
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.