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]:
-
Binary tree equivalence (
pandq):- An empty tree is represented by
None, and each non-empty node is a 3-element list[val, left, right], wherevalis an integer andleftandrightare child subtrees (each either another 3-element node list orNone). trees_matchisTrueif and only ifpandqhave identical branching structure and matchingvalintegers at every corresponding node position; otherwisetrees_matchisFalse.
- An empty tree is represented by
-
Balanced bracket check (
s):- Given a string
scomposed of'(',')','[',']','{', and'}',brackets_validisTrueif 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; otherwisebrackets_validisFalse.
- Given a string
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 depth10^4).-2^31 <= val <= 2^31 - 1for every node value.0 <= len(s) <= 10^5, andscontains only characters from"()[]{}".
Step-by-step walkthrough
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]:- Binary tree equality (
pandq): In the judge harness, an empty tree isNone, 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- 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^4tree nodes and10^5characters, both checks must run in linear time.- Binary tree equality (
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—returnFalseimmediately. - Different values (
val_p != val_q): ReturnFalseimmediately. - 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^4nodes does not have to be balanced—it can be a single chain10,000levels deep. Python's default call-stack limit is1,000frames, so a recursive function raisesRecursionErroron deep chains. Storing pending(node_p, node_q)pairs in our own Python listpair_stackperforms the exact same traversal with no recursion-depth limit.- Both
Write is_same_tree with an explicit pair stack
Here is how
pair_stackcatches the shape mismatch in Example 2 (p = [4, [9, None, None], None]vsq = [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_pkeeps 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 TruePart 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 + ")" * 50000takes50,000full 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_stackis non-empty and its top element (open_stack[-1]) is the matching opener, then pop it. - After scanning the whole string,
open_stackmust 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- Counting each bracket type fails because
Write is_valid_brackets
Mapping each closing bracket to its required opener in
MATCHING_OPENERlets 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) == 0Design 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 (Nonevs 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),0and 32-bit signed integer limits (-2^31and2^31 - 1), and two10^4-node chains (verifies noRecursionError). - 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, verifiesO(L)speed).
- Tree tests: both empty (
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 forTrue->[True, True]. - Example 2: Node
9sits on the left inpand on the right inq(False), and"{[(])}"crosses'('with']'(False) ->[False, False]. - Example 3: Right leaf
12 != 99fails value comparison (False), while""leavesopen_stackempty (True) ->[False, True].
- Example 1: Identical 4-node asymmetric trees give
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:
- Trees:
pair_stackstarts with(p, q). Popping the roots shows both exist with value4, so we push([9, None, None], None)and(None, [9, None, None]). Next we pop(None, [9, None, None]): one side isNonewhile the other is a node, proving the shapes differ ->False. - Brackets: Scanning
"{[(])}"pushes'{','[', and'('ontoopen_stack(['{', '[', '(']). Next arrives']', which requires'['on top, butopen_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). Inis_same_tree, we only push children when both nodes exist and match, so we expand at mostmin(N, M)node pairs withO(1)work per pair. Inis_valid_brackets, we scan each of theLcharacters once, performing at most oneO(1)list append or pop per character. - Space:
O(H + L). During depth-first tree comparison,pair_stackholds the active root-to-node path plus at most one waiting sibling pair per level, which isO(H)pairs (O(min(N, M))in the worst case of a skewed chain). Inis_valid_brackets,open_stackholds at mostLcharacters (reached whensconsists solely of opening brackets).
Edge cases
- Empty trees (
None, Nonevs oneNone): Two empty trees returnTrue; one empty tree and one non-empty tree returnFalseon 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 aNonealigns with a non-Nonechild. - Zero and 32-bit extreme values: Testing
node_p is Nonerather than truthiness (not node_pornot val_p) handles0, negative numbers,-2147483648, and2147483647cleanly. - Skewed
10^4-node chains: An explicit list stack handles10,000-deep chains without touching Python's recursion limit. - Empty bracket string
"": The loop runs zero times andlen(open_stack) == 0returnsTrue. - Closing bracket first or leftover openers: Strings like
"]["and"())("fail onnot open_stack, while strings like"(("and"([]"fail the finallen(open_stack) == 0check (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"]"raisesIndexErrorinstead of returningFalse. - Returning
Trueright after the bracket loop: Forgettingreturn len(open_stack) == 0wrongly 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 triggersRecursionError. - 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.dequequeue instead of a stack; it has the sameO(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 everyNonechild uniquely encodes tree structure, though building both lists always takesO(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
qis a subtree ofpif some node insidephas the exact same values and downward structure asqall the way to the leaves. The simplest method walkspiteratively and callsis_same_tree(node, q)whenevernode[0] == q[0], takingO(N * M)time in the worst case. To guaranteeO(N + M)time, serialize both trees in preorder as lists of tokens—including an explicit'#'token for everyNonechild so partial branches cannot match—and run a linear-time pattern search (such as the Knuth-Morris-Pratt algorithm) to check whetherq's token list appears contiguously insidep'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_stackwith[(root[1], root[2])](returningTrueimmediately ifroot is None) and keep the exact sameNoneand value checks, but cross-pair the children by pushing(left_a, right_b)and(right_a, left_b). Each mirror pair is checked once inO(N)time andO(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: add1for'(', subtract1for')', returnFalseimmediately ifbalance < 0, and checkbalance == 0at the end, usingO(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 requiresO(L)information to remember the exact sequence of open types.
Follow-up questions
- How would you determine whether binary tree q appears as an exact subtree anywhere inside binary tree p?
- How can you adapt the paired-stack tree traversal to test whether a single binary tree is a mirror image of itself?
- 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?
Similar questions
- Combined Behavioral and Practical Software Engineering Deep Dive
- Java Design, Scaling, and Testing Follow-Ups
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance