↓Skip to main content
  1. LeetCode/

LeetCode 144: Binary Tree Preorder 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: Runtime Error → Wrong Answer ×2 → Runtime Error → Accepted ×4

Approach
#

Pre-order is root, left, right, recording on pop (Tree). A stack is last in, first out, so push the right child before the left to pop the left first.

My Attempts
#

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

Solution
#

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

Complexity
#

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

Mistakes to Avoid
#

  • Push in the reverse of the order you want to process.

Interview Explanation
#

Pre-order is root, left, right: pop and record, pushing right before left so the left subtree comes first. Time O(n).

Related

LeetCode 94: Binary Tree Inorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 note: iterative in-order traversal, pushing nodes while going left, recording on pop, then turning to the right subtree
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