Binary Tree Lateral Perspective and Zero-Sum Triplet Extraction
Trees & GraphsModel answerLast updated
Solve two fundamental interview tasks: identifying the rightmost nodes of a binary tree by level and finding non-duplicate zero-sum triplets in an un-ordered array.
This multi-part problem tests tree traversal methods and pointer manipulation on sorted arrays.
Task 1: Right-Side Binary Tree Silhouette
Given the root node of a binary tree, list the node values that are visible when viewing the tree from its right flank. Construct the output starting from the top layer to the deepest level.
Example
Input Tree:
10
/ \
20 30
\ \
50 40
Output: [10, 30, 40]
Limits
- Tree size is between
0and10,000nodes. - Values of nodes fall within standard 32-bit integer limits.
Task 2: Non-Duplicate Zero-Sum Triplets
Given an integer array values, find all unique triplets [a, b, c] contained in the array such that a + b + c = 0.
The result set must contain no duplicate triplets (e.g., [ -1, 0, 1 ] and [ 0, 1, -1 ] are considered identical). The output ordering of triplets and internal values does not matter.
Example
Input: values = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Limits
3 <= values.length <= 3000-10^5 <= values[i] <= 10^5
Hints
Hint 1
For Task 1: A simple right-branch traversal will fail if a left subtree goes deeper than the right subtree. Think level by level.
Hint 2
For Task 2: Sorting the input array converts the problem into a fixed element plus a two-pointer search.
Hint 3
To avoid duplicate triplets in Task 2 without using a hash set, advance your pointers past equal consecutive values.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: Binary Tree Silhouette (Right-Side View)
Method Overview
A common mistake is attempting to follow only .right pointers. If the left subtree extends deeper than the right, its deeper levels are visible from the right side because nothing obstructs them.
The most robust approach is Level-Order Traversal (BFS) using a double-ended queue. We process the tree level by level. The last node processed at any given depth level represents the rightmost node visible from that elevation.
Alternatively, a Depth-First Search (DFS) visiting right children before left children works: we maintain the current recursion depth and add the node's value to our output array if we are reaching that depth level for the first time.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the total count of nodes. Every node enters and leaves the queue once.
- Space Complexity: $\mathcal{O}(W)$ where $W$ is the maximum width of the tree (up to $\mathcal{O}(N)$ for a complete binary tree's bottom layer).
Task 2: Unique Zero-Sum Triplets (3Sum)
Method Overview
A naive three-loop check takes $\mathcal{O}(N^3)$ time. We can achieve $\mathcal{O}(N^2)$ time using Sorting + Two Pointers:
- Sort
valuesin non-decreasing order. - Iterate through
valueswith indexi, treatingvalues[i]as the fixed first element ($a$). - Use two pointers,
left = i + 1andright = len(values) - 1, to find pairs such thatvalues[left] + values[right] == -values[i].- If the sum is smaller than
0, incrementleft. - If the sum is larger than
0, decrementright. - If the sum equals
0, record the triplet and move both pointers inward.
- If the sum is smaller than
- Skip duplicates to prevent redundant triplets:
- Skip
values[i]if it equalsvalues[i - 1]. - After finding a valid triplet, advance
leftpast any elements equal tovalues[left].
- Skip
Complexity Analysis
- Time Complexity: $\mathcal{O}(N^2)$. Sorting requires $\mathcal{O}(N \log N)$ time. The outer loop runs $N$ times, and the inner two-pointer scan processes the array in linear time $\mathcal{O}(N)$.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space (excluding memory needed for array sorting and the output list).
Python Code
from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val: int = 0, left: 'Optional[TreeNode]' = None, right: 'Optional[TreeNode]' = None):
self.val = val
self.left = left
self.right = right
def get_right_side_view(root: Optional[TreeNode]) -> List[int]:
"""Extract values of nodes visible from the right side of the tree."""
if not root:
return []
right_view = []
queue = deque([root])
while queue:
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
# The last element in the current level queue is the rightmost node
if i == level_length - 1:
right_view.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return right_view
def find_zero_sum_triplets(values: List[int]) -> List[List[int]]:
"""Find all unique triplets that sum to zero."""
values.sort()
triplets = []
n = len(values)
for i in range(n - 2):
# Optimization: If the fixed element is positive, no sum can equal zero
if values[i] > 0:
break
# Skip duplicate values for the first element
if i > 0 and values[i] == values[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
current_sum = values[i] + values[left] + values[right]
if current_sum < 0:
left += 1
elif current_sum > 0:
right -= 1
else:
triplets.append([values[i], values[left], values[right]])
left += 1
right -= 1
# Skip duplicate values for the second element
while left < right and values[left] == values[left - 1]:
left += 1
return triplets