↓Skip to main content
  1. LeetCode/

LeetCode 102: Binary Tree Level Order Traversal

·1 min· ·
LeetCode Medium Tree Breadth-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: medium First Attempt: 2022-10-29

  • Submissions: Wrong Answer → Runtime Error ×2 → Time Limit Exceeded → Wrong Answer → Runtime Error → Wrong Answer → Accepted → Wrong Answer → Accepted ×4

Approach
#

BFS naturally goes level by level (Tree Template 2). Each round takes every node on the current level, records their values, and collects their children as the next level.

My Attempts
#

Most failures were on the empty tree: returning [[]] (an extra empty level), using an undefined variable, or a loop with no exit (TLE); one returned [3] instead of [[3]].

Solution
#

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        res, level = [], [root] if root else []
        while level:
            res.append([n.val for n in level])
            level = [c for n in level for c in (n.left, n.right) if c]
        return res

Complexity
#

Time O(n), space O(w) for the widest level w.

Mistakes to Avoid
#

  • An empty tree returns [], not [[]].

Interview Explanation
#

With BFS, each round handles a whole level: record its values, then gather all children as the next level until none remain. Time O(n).

Related

LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 230: Kth Smallest Element in a BST
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 230 note: a BST’s in-order traversal is ascending, so stop an iterative in-order walk at the k-th node
LeetCode 98: Validate Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 98 note: every node has a valid range (low, high); going left the upper bound becomes the node and going right the lower bound does; comparing parent and child is not enough
LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 993: Cousins in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 note: cousins share a depth but not a parent; record x’s and y’s depth and parent during DFS and compare