↓Skip to main content
  1. LeetCode/

LeetCode 94: Binary Tree Inorder Traversal

·1 min· ·
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-07-20

  • Submissions: Wrong Answer ×2 → Runtime Error ×2 → Accepted → Runtime Error ×2 → Accepted → Runtime Error → Accepted ×3

Approach
#

In-order is left, root, right. Recursion is direct; iteratively you simulate the call stack yourself (Tree):

  1. From the current node, walk left, pushing every node passed.
  2. At the bottom, pop a node and record it (its left side is done).
  3. Move to its right subtree and repeat.

My Attempts
#

Most REs had the same cause: reading root.left / root.val on an empty tree (root is None). Another used an undefined variable (NameError).

Solution
#

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

Complexity
#

Time O(n), space O(h) for height h.

Mistakes to Avoid
#

  • The outer condition is cur or stack; stop only when both are empty.

Interview Explanation
#

I simulate recursion with a stack: push while going left, pop and record at the bottom, then turn to the right subtree. Each node enters and leaves once. Time O(n), space O(h).

Related

LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first
LeetCode 83: Remove Duplicates from Sorted List
·2 mins
LeetCode Easy Linked-List
LeetCode 83 note: sorted, so duplicates are adjacent; skip cur.next while it equals cur, and advance only otherwise
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1