SDE & MLE Prep

94. Binary Tree Inorder Traversal

Problem

Return the in-order traversal (left subtree, node, right subtree) of a binary tree.

Example: [1,null,2,3] → [1,3,2]

Constraints: follow-up: iteratively.

Iterative in-order: push the left spine, pop a node, visit it, then continue with its right subtree. (Morris traversal does it in O(1) space by threading.)

Complexity: O(n) time, O(h) space.

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res, st, node = [], [], root
        while st or node:
            while node:
                st.append(node)
                node = node.left
            node = st.pop()
            res.append(node.val)
            node = node.right
        return res