Interview Questions
- Binary Tree Level Order Traversalcoding
Title:
Binary Tree Level Order Traversal
Problem:
Given the root of a binary tree, return the level order traversal of its node values. (i.e., from left to right, level by level).
Function Signature:
def level_order(root: Optional[TreeNode]) -> List[List[int]]:Input:
root: Optional[TreeNode] — the root node of a binary tree
Output:
A list of lists of integers representing values at each level from top to bottom
Sample Input:
[3, 9, 20, null, null, 15, 7]
Sample Output:
[[3], [9, 20], [15, 7]]
Example:
For the binary tree: 3 / \ 9 20 /
15 7 The level order traversal returns [[3], [9, 20], [15, 7]].Constraints:
The number of nodes in the tree is in the range [0, 2000]. -1000 ≤ Node.val ≤ 1000.
Hints:
Use a queue (breadth-first search) to process each node level by level. Enqueue the children of each node as you go.
Follow-up:
Can you solve it using recursion? How would you return the level order traversal from bottom to top (reverse level order)?