Skip to main content
Back to ChallengesLeft View / Right View of Binary TreeMedium 25 min

Left View / Right View of Binary Tree

Given the root of a binary tree, return both the **left view** and **right view**.

- **Left view**: The first node visible when looking from the left side at each level.

- **Right view**: The last node visible when looking from the right side at each level.

Examples

Input: root = [1,2,3,4,5,6,7]
Output: { left: [1,2,4], right: [1,3,7] }
First and last node of each level.
Input: root = [1,2,null,3]
Output: { left: [1,2,3], right: [1,2,3] }
Only one node per level.

Constraints

  • Number of nodes in [0, 500]

Complexity Analysis

Time
O(n)
BFS visits all nodes.
Space
O(n)
queue storage.

Test Cases

#1 Full tree
Input: [1,2,3,4,5,6,7]
Expected: {"left":[1,2,4],"right":[1,3,7]}
#2 Left-skewed
Input: [1,2,null,3]
Expected: {"left":[1,2,3],"right":[1,2,3]}
#3 Empty tree
Input: []
Expected: {"left":[],"right":[]}
JavaScript
Output
Click "Run Code" to see output here...