Right Edge of a Tree and Minimal Bracket Removal
Trees & GraphsModel answerLast updated
Two linked tasks: list the nodes visible from the right of a binary tree, and delete the fewest parentheses from a string so the rest is balanced.
Answer both parts. For each, explain your approach, give its time and space complexity, and write code.
Part 1: Right edge of a binary tree
You stand to the right of a binary tree and look at it. Given its root, return the values of the nodes you can see, ordered from the top level to the bottom level.
Example
- Input:
root = [1,2,3,null,5,null,4](level-order,nullmeans no child) - Output:
[1,3,4]
Part 2: Fewest deletions to balance parentheses
You are given a string s made of lowercase letters, ( and ). Delete as few parentheses as possible so that the remaining string is balanced. Letters are never deleted and do not affect balance.
A string is balanced when every ( is paired with a later ), every ) is paired with an earlier (, and the pairs nest properly.
If several results are possible, return any one that is balanced and uses the minimum number of deletions.
Examples
| Input | Output |
|---|---|
a)b(c)d | ab(c)d |
))(( | `` (empty string) |
(a(b(c)d) | a(b(c)d) |
What to cover
- The core idea of each solution and why it is correct, including why Part 2 removes the minimum number of characters.
- Edge cases: empty tree, one node, one-sided trees, an empty string, a string with no parentheses, a string that is already balanced.
- Complexity of both solutions.
Hints
Hint 1
For Part 1, think about which node at each depth hides all the others. Is following only right-child pointers enough, or can a node on the left side of the tree be visible?
Hint 2
Part 1 can be done level by level with a queue: the node you want per level is the last one in left-to-right order. A depth-first alternative visits the right child first and records a node only when it is the first one seen at a new depth.
Hint 3
For Part 2, scan left to right and keep the indices of `(` that have not been paired yet. A `)` either pairs with the latest such index or, if none exists, can never be paired.
Hint 4
After the scan, every `(` still waiting is also unpairable. Mark all unpairable indices, then rebuild the string without them.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Right edge of a binary tree
Idea
At each depth, exactly one node is seen: the rightmost node at that depth. Every other node at that depth is hidden behind it. So the answer has one value per level, and we need the last node of each level.
Following only right pointers is wrong. If the right branch ends at depth 2 but the left branch continues to depth 3, the depth-3 node on the left is visible. In [1,2,3,null,5,null,4] the levels are [1], [2,3], [5,4], and the last values are 1, 3, 4. If node 3 had no right child, node 5 would be visible at depth 2 instead of 4.
Approach: level-order traversal
- If the root is empty, return
[]. - Put the root in a queue.
- While the queue is not empty, take its current size
k. Theseknodes are one level. Pop them one by one, enqueue their left child then their right child, and record the value of thek-th popped node.
Children are enqueued left before right, so each level is processed left to right and the last node popped is the rightmost one.
from collections import deque
def right_view(root):
if root is None:
return []
out = []
q = deque([root])
while q:
k = len(q)
for i in range(k):
node = q.popleft()
if i == k - 1:
out.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return out
Complexity. Time is O(n), since each node enters and leaves the queue once. Space is O(w), where w is the maximum width of the tree, which is O(n) in the worst case.
Alternative. A DFS that visits right before left and appends a value whenever depth == len(out) also runs in O(n) time. Its space is O(h) for the recursion, which can overflow the call stack on very deep, skewed trees unless you convert it to an explicit stack.
Edge cases. An empty tree gives []. A single node gives [root.val]. A left-skewed chain shows every node. A deep left subtree under a shallow right subtree contributes its deeper nodes.
Part 2: Fewest deletions to balance parentheses
Idea
Pair brackets the way a human would. Walk through the string and keep a stack of indices of ( that are still open.
- On
(, push its index. - On
), if the stack is non-empty, pop it, which pairs this)with the nearest open(. If the stack is empty, nothing can pair with this), so mark it for deletion. - When the scan ends, any indices left in the stack are
(characters with no partner. Mark them for deletion too. - Letters are ignored.
Then build the result from the unmarked characters.
def make_balanced(s):
chars = list(s)
open_idx = []
for i, c in enumerate(chars):
if c == '(':
open_idx.append(i)
elif c == ')':
if open_idx:
open_idx.pop()
else:
chars[i] = ''
for i in open_idx:
chars[i] = ''
return ''.join(chars)
Trace on (a(b(c)d). The scan pushes 0, 2, 4. The ) at 6 pops 4, and the ) at 8 pops 2. Index 0 remains, so it is deleted, giving a(b(c)d).
For ))((, both ) are dropped during the scan and both ( are left on the stack, so the result is the empty string.
Why the result is valid
Every kept ) was paired with a kept ( to its left, and every kept ( was paired with a kept ) to its right. Because pairing is stack-based, the pairs nest and never cross, so the result is balanced.
Why the removal count is minimal
Let D be the largest value of (closes minus opens) over all prefixes of the string. That is the number of ) the scan discards.
- Some prefix has
Dmore)than(. Deleting(cannot help, and the only way to fix that prefix is to delete at leastDof the)in it. So at leastDcloses must go. - Let
OandCbe the total counts of(and). A balanced string has equal counts, and at mostC - Dcloses can survive, so at mostC - Dopens can survive. At leastO - (C - D)opens must go.
The algorithm deletes exactly D closes and leaves exactly O - (C - D) opens unpaired, so it meets both lower bounds and cannot be beaten.
Complexity
Time is O(n) for one pass plus a join. Space is O(n) for the character list and the stack.
Edge cases
- Empty string, letters only, or an already balanced string: returned unchanged.
- Only
)or only(: all of them are removed, and any letters stay. - A single stray
(at the front of a deeply nested string, as in the third example.
Follow-up: constant extra space
Use two passes with counters instead of a stack. Going forward, keep a balance count and drop any ) that would make it negative. Going backward over the result, drop as many ( as the leftover balance says are unmatched, starting from the right. This removes the rightmost surplus ( rather than the earliest unmatched one. On (a(b(c)d) it produces (a(bc)d), which is also balanced and also minimal. That is acceptable because any valid answer is allowed.
Common mistakes
- In Part 1, walking only down the right spine.
- In Part 1, forgetting the empty tree.
- In Part 2, using a plain counter in a single pass, which leaves unmatched
(in the output. - In Part 2, deleting a
(or)that was already paired, or removing letters. - In Part 2, building the output by slicing the string inside the loop, which makes the solution O(n²).