Binary Tree Level Order Traversal
Updated
Problem statement
You are given the root of a binary tree. Return the values of its nodes level by level: first the root's level, then the level below it, and so on. Within each level, list the values from left to right.
Return one list per level. If the tree is empty, return an empty list.
Follow-up: suppose you only need to print each level on its own line. Can you print the levels as you go, without first storing all of them in a list of lists?
Function
levelOrder(root: TreeNode) → List<List<Integer>>Examples
Example 1
root = [8,3,10,null,6,9,14,4]return = [[8],[3,10],[6,9,14],[4]]Level 0 is the root, 8. Level 1 has its children 3 and 10. Level 2 has 6 (the right child of 3), then 9 and 14 (the children of 10). Level 3 has 4, the left child of 6.
Example 2
root = []return = []The tree is empty, so there are no levels.
Example 3
root = [-5,null,2,null,7]return = [[-5],[2],[7]]No node has a left child: -5 has only the right child 2, and 2 has only the right child 7, so every level holds one value: -5, then 2, then 7.
Constraints
- The number of nodes in the tree is in the range
[0, 2000]. -1000 <= Node.val <= 1000- The height of the tree (the number of nodes on the longest path from the root down to a leaf) is at most
500.
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- Binary Tree Spiral Level OrderAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Zigzag Level-Order TraversalFlipkart · ONSITE INTERVIEW
- Binary Tree Zigzag Level Order TraversalLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Diameter of an Acyclic Undirected GraphSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Binary Tree Nodes at Distance KApple · ONSITE INTERVIEWApple interview questions
- Bottom View of a Binary TreeOracle · PHONE SCREEN · ONSITE INTERVIEWOracle interview questions
- Find the Tree DiameterAdyen · ONSITE INTERVIEWAdyen interview questions
- Top View of a Binary TreeCapillary Technologies · ONSITE INTERVIEWCapillary Technologies interview questions
- Binary Tree Nodes at Distance KGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions