KatInterview

Right Edge of a Tree and Minimal Bracket Removal

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbinary-treebfsstack

Last 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, null means 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

InputOutput
a)b(c)dab(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.