Binary Tree Equality and Bracket Validation

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement solve_tree_equality_and_brackets(p, q, s) to evaluate two independent data-structure checks in a single call and return [trees_match, brackets_valid]:

  1. Binary tree equivalence (p and q):

    • An empty tree is represented by None, and each non-empty node is a 3-element list [val, left, right], where val is an integer and left and right are child subtrees (each either another 3-element node list or None).
    • trees_match is True if and only if p and q have identical branching structure and matching val integers at every corresponding node position; otherwise trees_match is False.
  2. Balanced bracket check (s):

    • Given a string s composed of '(', ')', '[', ']', '{', and '}', brackets_valid is True if and only if every opening bracket is closed by the matching bracket kind, nested brackets close in last-opened-first-closed order, and every closing bracket pairs with an earlier unmatched opener; otherwise brackets_valid is False.

Examples

Example 1

Input:
  p = [10, [5, None, [7, None, None]], [20, None, None]]
  q = [10, [5, None, [7, None, None]], [20, None, None]]
  s = "{[()]}[]"

Output:
  [True, True]

Walk-through: Both p and q have root 10, left child 5 with right grandchild 7, and right child 20 (True). In "{[()]}[]", the nested "{[()]}" closes from the inside out and is followed by a matched "[]" pair (True).

Example 2

Input:
  p = [4, [9, None, None], None]
  q = [4, None, [9, None, None]]
  s = "{[(])}"

Output:
  [False, False]

Walk-through: Node 9 is a left child in p but a right child in q, so their structures differ (False). In "{[(])}", ']' appears while '(' is still the innermost open bracket (False).

Example 3

Input:
  p = [8, [3, None, None], [12, None, None]]
  q = [8, [3, None, None], [99, None, None]]
  s = ""

Output:
  [False, True]

Walk-through: Although p and q have the same 3-node layout, their right children hold different values (12 vs 99, giving False). An empty string has zero unmatched brackets (True).

Constraints

  • 0 <= nodes(p), nodes(q) <= 10^4 (trees may be arbitrarily skewed, including single-branch chains of depth 10^4).
  • -2^31 <= val <= 2^31 - 1 for every node value.
  • 0 <= len(s) <= 10^5, and s contains only characters from "()[]{}".

Step-by-step walkthrough

  1. Understand the two subproblems and inputs

    We need to solve two independent checks and return both answers in a two-element list [trees_equal, brackets_valid]:

    1. Binary tree equality (p and q): In the judge harness, an empty tree is None, and a non-empty node is a 3-element list [val, left_child, right_child]. Two trees are equal if and only if they have the exact same structure and identical node values at every matching position:
    Example 1 (equal -> True)               Example 2 (different shape -> False)
       10             10                        4              4
      /  \           /  \                      /                \
     5   20         5   20                    9                  9
      \              \                  [4,[9,..],None]    [4,None,[9,..]]
       7              7
    
    1. Valid brackets (s): Given a string of '(', ')', '[', ']', '{', '}', check that every closing bracket matches an earlier opening bracket of the same type in proper nested order, with no unclosed brackets left over.

    With up to 10^4 tree nodes and 10^5 characters, both checks must run in linear time.

  2. Part 1 idea: walk both trees in lockstep

    To compare two trees, start with the root pair (p, q) and check corresponding pairs (node_p, node_q) position by position:

    • Both None: Both trees are empty at this spot, so keep going.
    • Exactly one None: One tree has a node where the other has nothing, so their shapes differ—return False immediately.
    • Different values (val_p != val_q): Return False immediately.
    • Same values: Pair up (left_p, left_q) and (right_p, right_q) so both subtrees are checked in lockstep too.

    Why use an explicit stack list instead of recursion? A tree with 10^4 nodes does not have to be balanced—it can be a single chain 10,000 levels deep. Python's default call-stack limit is 1,000 frames, so a recursive function raises RecursionError on deep chains. Storing pending (node_p, node_q) pairs in our own Python list pair_stack performs the exact same traversal with no recursion-depth limit.

  3. Write is_same_tree with an explicit pair stack

    Here is how pair_stack catches the shape mismatch in Example 2 (p = [4, [9, None, None], None] vs q = [4, None, [9, None, None]]):

    Step   Popped (node_p, node_q)          Check                pair_stack after step
    ------------------------------------------------------------------------------------------------
    start  -                                -                    [([4,[9,None,None],None], [4,None,[9,None,None]])]
    1      ([4,[9,..],None], [4,None,[9,..]])  val 4 == 4 (ok)   [([9,None,None], None), (None, [9,None,None])]
    2      (None, [9,None,None])            one is None -> False! (stops immediately)
    

    Unpacking val_p, left_p, right_p = node_p keeps each node check clear and readable:

    def is_same_tree(p: Optional[List], q: Optional[List]) -> bool:
        # Each non-empty tree node is [val, left_child, right_child], e.g. [4, [9, None, None], None].
        # pair_stack: LIFO list of (node_p, node_q) pairs at corresponding positions in both trees.
        # Using an explicit stack avoids Python's ~1000-frame RecursionError on 10^4-node chain trees.
        pair_stack: List[Tuple[Optional[List], Optional[List]]] = [(p, q)]
    
        while pair_stack:
            node_p, node_q = pair_stack.pop()
    
            # Both positions are empty: this branch matches so far.
            if node_p is None and node_q is None:
                continue
    
            # Only one position is empty: the two trees have different shapes.
            if node_p is None or node_q is None:
                return False
    
            val_p, left_p, right_p = node_p
            val_q, left_q, right_q = node_q
    
            if val_p != val_q:
                return False
    
            # Queue both left children together and both right children together.
            pair_stack.append((left_p, left_q))
            pair_stack.append((right_p, right_q))
    
        return True
    
  4. Part 2 idea: match brackets with a stack

    Why do simpler shortcuts fail on brackets?

    • Counting each bracket type fails because "([)]" has one '(', one ')', one '[', and one ']', yet ')' closes before the inner '[' is closed.
    • Repeatedly deleting "()", "[]", "{}" substrings is too slow because "(" * 50000 + ")" * 50000 takes 50,000 full string passes (O(L^2) time).

    Because the most recently opened bracket must always be the first one closed, a stack (last-in, first-out) fits the rule directly:

    • Push every opening bracket onto open_stack.
    • When a closing bracket arrives, check that open_stack is non-empty and its top element (open_stack[-1]) is the matching opener, then pop it.
    • After scanning the whole string, open_stack must be empty so no unclosed openers remain.

    Compare Example 1's valid "{[()]}[]" with Example 2's invalid "{[(])}":

    Trace 1: s = "{[()]}[]"                   Trace 2: s = "{[(])}"
    ch   action        open_stack             ch   action                   open_stack
    ------------------------------------      ------------------------------------------------
    '{'  push          ['{']                  '{'  push                     ['{']
    '['  push          ['{', '[']             '['  push                     ['{', '[']
    '('  push          ['{', '[', '(']        '('  push                     ['{', '[', '(']
    ')'  matches '('   ['{', '[']             ']'  need '[', top is '(' ->  return False!
    ']'  matches '['   ['{']
    '}'  matches '{'   []
    '['  push          ['[']
    ']'  matches '['   []  -> empty -> True
    
  5. Write is_valid_brackets

    Mapping each closing bracket to its required opener in MATCHING_OPENER lets one clean check handle all three bracket types:

    OPENERS = {"(", "[", "{"}
    MATCHING_OPENER = {")": "(", "]": "[", "}": "{"}
    
    
    def is_valid_brackets(s: str) -> bool:
        # open_stack: LIFO list of unmatched opening brackets seen so far, e.g. ['(', '['].
        open_stack: List[str] = []
    
        for ch in s:
            if ch in OPENERS:
                open_stack.append(ch)
            elif ch in MATCHING_OPENER:
                # Every closer must match the most recently opened, still-unclosed bracket.
                expected_opener = MATCHING_OPENER[ch]
                if not open_stack or open_stack[-1] != expected_opener:
                    return False
                open_stack.pop()
            else:
                return False
    
        # Valid only when every opening bracket was closed by the end of the string.
        return len(open_stack) == 0
    
  6. Design thorough normal and edge-case tests

    A complete test suite should cover both typical inputs and structural corner cases:

    • Tree tests: both empty (None, None -> True), one empty (None vs single node -> False), identical balanced or asymmetric trees (True), same shape with one differing value (False), left child vs right child ([4, [9, None, None], None] vs [4, None, [9, None, None]] -> False), swapped left/right subtrees (False), 0 and 32-bit signed integer limits (-2^31 and 2^31 - 1), and two 10^4-node chains (verifies no RecursionError).
    • Bracket tests: empty string "" (True), nested plus sequential "{[()]}[]" (True), deeply nested "{[()()]}" (True), wrong closer "(]" (False), crossed nesting "{[(])}" (False), closer before opener "][" and "())(" (False), leftover opener "([]" (False), and "(" * 50000 + ")" * 50000 (True, verifies O(L) speed).
  7. Combine both checks in solve_tree_equality_and_brackets

    The entry function calls both helpers independently and returns their two booleans:

    def solve_tree_equality_and_brackets(
        p: Optional[List], q: Optional[List], s: str
    ) -> List[bool]:
        return [is_same_tree(p, q), is_valid_brackets(s)]
    
    • Example 1: Identical 4-node asymmetric trees give True, and "{[()]}[]" opens and closes every pair cleanly for True -> [True, True].
    • Example 2: Node 9 sits on the left in p and on the right in q (False), and "{[(])}" crosses '(' with ']' (False) -> [False, False].
    • Example 3: Right leaf 12 != 99 fails value comparison (False), while "" leaves open_stack empty (True) -> [False, True].
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Opening brackets and the exact opener required by each closing bracket.
    OPENERS = {"(", "[", "{"}
    MATCHING_OPENER = {")": "(", "]": "[", "}": "{"}
    
    
    def is_same_tree(p: Optional[List], q: Optional[List]) -> bool:
        # Each non-empty tree node is [val, left_child, right_child], e.g. [4, [9, None, None], None].
        # pair_stack: LIFO list of (node_p, node_q) pairs at corresponding positions in both trees.
        # Using an explicit stack avoids Python's ~1000-frame RecursionError on 10^4-node chain trees.
        pair_stack: List[Tuple[Optional[List], Optional[List]]] = [(p, q)]
    
        while pair_stack:
            node_p, node_q = pair_stack.pop()
    
            # Both positions are empty: this branch matches so far.
            if node_p is None and node_q is None:
                continue
    
            # Only one position is empty: the two trees have different shapes.
            if node_p is None or node_q is None:
                return False
    
            val_p, left_p, right_p = node_p
            val_q, left_q, right_q = node_q
    
            if val_p != val_q:
                return False
    
            # Queue both left children together and both right children together.
            pair_stack.append((left_p, left_q))
            pair_stack.append((right_p, right_q))
    
        return True
    
    
    def is_valid_brackets(s: str) -> bool:
        # open_stack: LIFO list of unmatched opening brackets seen so far, e.g. ['(', '['].
        open_stack: List[str] = []
    
        for ch in s:
            if ch in OPENERS:
                open_stack.append(ch)
            elif ch in MATCHING_OPENER:
                # Every closer must match the most recently opened, still-unclosed bracket.
                expected_opener = MATCHING_OPENER[ch]
                if not open_stack or open_stack[-1] != expected_opener:
                    return False
                open_stack.pop()
            else:
                return False
    
        # Valid only when every opening bracket was closed by the end of the string.
        return len(open_stack) == 0
    
    
    def solve_tree_equality_and_brackets(
        p: Optional[List], q: Optional[List], s: str
    ) -> List[bool]:
        return [is_same_tree(p, q), is_valid_brackets(s)]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Both subproblems use a stack—a last-in, first-out (LIFO) list where items are always added and removed at the top, like a pile of trays. In a binary tree (a structure where each node holds a value, a left child, and a right child), imagine placing one finger on the root of p and another on the root of q, checking that both fingers see the same value, and pushing their paired left children and paired right children onto pair_stack so both trees are explored in lockstep. For bracket validation, imagine stacking an opening bracket each time you read '(', '[', or '{'; whenever ')', ']', or '}' arrives, it must match and pop the bracket currently sitting on top of open_stack, leaving nothing behind at the end.

Naive approaches break on structure, recursion depth, or speed. For trees, comparing flat lists of node values loses shape information unless empty children are recorded, while plain recursion crashes with RecursionError in Python when 10^4 nodes form a single chain deeper than Python's ~1,000-frame call-stack limit. For brackets, counting each bracket type ignores nesting order ("([)]" has balanced counts yet is invalid), and repeatedly replacing "()", "[]", and "{}" substrings scans the string up to L / 2 times (O(L^2) time, which stalls on 10^5 characters).

Walk through Example 2 (p = [4, [9, None, None], None], q = [4, None, [9, None, None]], s = "{[(])}") to see both stacks stop at the exact point of failure:

  1. Trees: pair_stack starts with (p, q). Popping the roots shows both exist with value 4, so we push ([9, None, None], None) and (None, [9, None, None]). Next we pop (None, [9, None, None]): one side is None while the other is a node, proving the shapes differ -> False.
  2. Brackets: Scanning "{[(])}" pushes '{', '[', and '(' onto open_stack (['{', '[', '(']). Next arrives ']', which requires '[' on top, but open_stack[-1] is '(' -> False.

Complexity

Let N and M be the number of nodes in trees p and q, let H be the smaller of the two trees' heights (longest root-to-leaf path length), and let L be the length of s.

  • Time: O(min(N, M) + L). In is_same_tree, we only push children when both nodes exist and match, so we expand at most min(N, M) node pairs with O(1) work per pair. In is_valid_brackets, we scan each of the L characters once, performing at most one O(1) list append or pop per character.
  • Space: O(H + L). During depth-first tree comparison, pair_stack holds the active root-to-node path plus at most one waiting sibling pair per level, which is O(H) pairs (O(min(N, M)) in the worst case of a skewed chain). In is_valid_brackets, open_stack holds at most L characters (reached when s consists solely of opening brackets).

Edge cases

  • Empty trees (None, None vs one None): Two empty trees return True; one empty tree and one non-empty tree return False on the very first pop.
  • Same node values in different shapes: Left-leaning [4, [9, None, None], None] and right-leaning [4, None, [9, None, None]] (or swapped left/right children) fail as soon as a None aligns with a non-None child.
  • Zero and 32-bit extreme values: Testing node_p is None rather than truthiness (not node_p or not val_p) handles 0, negative numbers, -2147483648, and 2147483647 cleanly.
  • Skewed 10^4-node chains: An explicit list stack handles 10,000-deep chains without touching Python's recursion limit.
  • Empty bracket string "": The loop runs zero times and len(open_stack) == 0 returns True.
  • Closing bracket first or leftover openers: Strings like "][" and "())(" fail on not open_stack, while strings like "((" and "([]" fail the final len(open_stack) == 0 check (note that any odd-length string is also guaranteed invalid).

Common mistakes

  • Popping from an empty bracket stack without checking if not open_stack: A string starting with ")" or "]" raises IndexError instead of returning False.
  • Returning True right after the bracket loop: Forgetting return len(open_stack) == 0 wrongly accepts unclosed strings such as "(((".
  • Using three integer counters instead of a stack: Separate counters for (), [], and {} cannot detect crossed brackets like "([)]".
  • Using plain recursion on 10^4-node trees in Python: Without an iterative stack, a degenerate linked-list-shaped tree triggers RecursionError.
  • Comparing single tree traversals without null markers: Two differently shaped trees (such as [1, [1, None, None], None] and [1, None, [1, None, None]]) can produce the exact same inorder or preorder value list.

Alternative approaches

  • Breadth-first tree comparison: Breadth-first traversal visits trees level by level using a collections.deque queue instead of a stack; it has the same O(min(N, M)) time complexity, while its peak memory scales with the widest tree level rather than the height.
  • Recursive tree comparison: Writing p[0] == q[0] and is_same_tree(p[1], q[1]) and is_same_tree(p[2], q[2]) is concise and clean whenever tree height is guaranteed small (such as balanced trees) or in languages without a tight call-stack cap.
  • Preorder serialization with null markers: Preorder traversal visits each node before its left and right subtrees; recording every node value plus a # token for every None child uniquely encodes tree structure, though building both lists always takes O(N + M) time and memory instead of stopping at the first mismatch.

Follow-up questions

  • How would you determine whether binary tree q appears as an exact subtree anywhere inside binary tree p? A tree q is a subtree of p if some node inside p has the exact same values and downward structure as q all the way to the leaves. The simplest method walks p iteratively and calls is_same_tree(node, q) whenever node[0] == q[0], taking O(N * M) time in the worst case. To guarantee O(N + M) time, serialize both trees in preorder as lists of tokens—including an explicit '#' token for every None child so partial branches cannot match—and run a linear-time pattern search (such as the Knuth-Morris-Pratt algorithm) to check whether q's token list appears contiguously inside p's token list.
  • How can you adapt the paired-stack tree traversal to test whether a single binary tree is a mirror image of itself? A tree is symmetric when its left subtree is a mirror image of its right subtree. Start pair_stack with [(root[1], root[2])] (returning True immediately if root is None) and keep the exact same None and value checks, but cross-pair the children by pushing (left_a, right_b) and (right_a, left_b). Each mirror pair is checked once in O(N) time and O(H) stack space.
  • When the input string uses only '(' and ')', you can validate it in O(1) auxiliary memory—why does that approach fail once '[' and '{' are added? With only one bracket type, you can replace the stack with a single integer balance = 0: add 1 for '(', subtract 1 for ')', return False immediately if balance < 0, and check balance == 0 at the end, using O(1) memory. That works because all open brackets on the stack would be identical '(' characters anyway, so only the stack's size matters. With multiple bracket types ((), [], {}), the order of types matters ("{[(])}" vs "{[()]}"), which requires O(L) information to remember the exact sequence of open types.

Follow-up questions

Similar questions

More Deutsche Bank interview questions

All 3 Deutsche Bank questions →