Return a Binary Tree in Level Order
AdobeSoftware Engineer · OnsiteLast updated
Return a binary tree's values grouped by depth in level order while preserving left-to-right order within each level. Handle empty, repeated-value, skewed, and very large trees without changing the requested nested output shape.
Problem
Given a binary tree, return its values in level order as a list of lists. Values at depth 0 appear in the first list, values at depth 1 in the second, and so on. Preserve left-to-right order within each level.
Function Contract
Implement levelOrder(root).
Constraints & Assumptions
- The tree contains at most
100,000nodes. - Node values are signed 32-bit integers and may repeat.
- Return an empty list for an empty tree.
Clarifying Questions to Ask
- Is a flat breadth-first list sufficient? No, group values by depth.
- Must left-to-right order be preserved? Yes.
- Can the tree be skewed? Yes.
- May the input contain shared or cyclic child references? No, it is a valid tree.
Example
tree = [3, 9, 20, null, null, 15, 7]
output = [[3], [9, 20], [15, 7]]
Evaluation Focus
- Groups nodes at the correct depth.
- Preserves child order and handles missing children.
- Avoids repeated list shifting with an inefficient queue representation.
- Runs in
O(n)time and usesO(w)queue space for maximum widthw.
Extensions to Discuss
- How would you stream one completed level at a time?
- How would zigzag level order change the collection step?
- What is the worst-case queue size for a balanced tree?
Hints
Hint 1
Freeze the current breadth: At the start of each breadth-first iteration, record the queue size; exactly that many nodes belong to the current level.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.