{"id":"same-tree","title":"Same Tree","difficulty":"easy","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-basics","concepts":["tree-dfs-basics"],"problemForm":"intro","companies":[],"category":"trees-graphs","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-trees","primaryParam":"p","secondaryParam":"q","sizeMetric":"node-count"},"description":"Given the roots of two binary trees, return whether the trees are structurally identical and every matching node has the same value.","examples":[{"input":"p = [1,2,3], q = [1,2,3]","output":"true","explanation":"Both trees have the same shape and the same values at every matching node."},{"input":"p = [1,2], q = [1,null,2]","output":"false","explanation":"The value 2 appears on different sides of the root, so the structures differ."},{"input":"p = [1,2,1], q = [1,1,2]","output":"false","explanation":"The shape is the same, but the left and right child values differ."}],"constraints":[{"id":"0-number-of-nodes-in-each-tree-100","text":"0 <= number of nodes in each tree <= 100","check":[{"kind":"sizeRange","target":"p","measure":"treeNodes","min":0,"max":100},{"kind":"sizeRange","target":"q","measure":"treeNodes","min":0,"max":100}]},{"id":"10-4-node-val-10-4","text":"-10^4 <= Node.val <= 10^4","check":[{"kind":"valueRange","target":"p","selector":"treeValues","min":-10000,"max":10000},{"kind":"valueRange","target":"q","selector":"treeValues","min":-10000,"max":10000}]},{"id":"both-structure-and-values-must-match","text":"Both structure and values must match"}],"starterCode":"# TraceCode provides TreeNode at runtime.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\nclass Solution:\n    def isSameTree(self, p: TreeNode | None, q: TreeNode | None) -> bool:\n        # Your code here\n        pass","functionName":"isSameTree","testCases":[{"id":"1","input":{"p":{"__type__":"TreeNode","__id__":"p-0","val":1,"left":{"__type__":"TreeNode","__id__":"p-1","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"p-2","val":3,"left":null,"right":null}},"q":{"__type__":"TreeNode","__id__":"q-0","val":1,"left":{"__type__":"TreeNode","__id__":"q-1","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"q-2","val":3,"left":null,"right":null}}},"expected":true,"description":"Same shape and values."},{"id":"2","input":{"p":{"__type__":"TreeNode","__id__":"p-10","val":1,"left":{"__type__":"TreeNode","__id__":"p-11","val":2,"left":null,"right":null},"right":null},"q":{"__type__":"TreeNode","__id__":"q-10","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"q-11","val":2,"left":null,"right":null}}},"expected":false,"description":"Same values but different structure."},{"id":"3","input":{"p":{"__type__":"TreeNode","__id__":"p-20","val":1,"left":{"__type__":"TreeNode","__id__":"p-21","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"p-22","val":1,"left":null,"right":null}},"q":{"__type__":"TreeNode","__id__":"q-20","val":1,"left":{"__type__":"TreeNode","__id__":"q-21","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"q-22","val":2,"left":null,"right":null}}},"expected":false,"description":"Same shape but different values."},{"id":"4","input":{"p":null,"q":null},"expected":true,"description":"Both trees empty."},{"id":"5","input":{"p":null,"q":{"__type__":"TreeNode","__id__":"q-30","val":0,"left":null,"right":null}},"expected":false,"description":"Only one tree is empty."},{"id":"h1","input":{"p":{"__type__":"TreeNode","val":1,"left":null,"right":null},"q":{"__type__":"TreeNode","val":1,"left":null,"right":null}},"expected":true,"description":"Two identical single-node trees match."},{"id":"h2","input":{"p":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","val":3,"left":null,"right":null}},"q":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","val":4,"left":null,"right":null}}},"expected":false,"description":"A value mismatch on one leaf makes the trees different."},{"id":"h3","input":{"p":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":null,"right":null},"right":null},"right":null},"q":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":null,"right":null},"right":null},"right":null}},"expected":true,"description":"A left-skewed tree can still match exactly."},{"id":"h4","input":{"p":{"__type__":"TreeNode","val":0,"left":null,"right":null},"q":null},"expected":false,"description":"A missing right-side tree still breaks structural equality."},{"id":"h5","input":{"p":{"__type__":"TreeNode","val":1,"left":null,"right":{"__type__":"TreeNode","val":2,"left":null,"right":null}},"q":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":2,"left":null,"right":null},"right":null}},"expected":false,"description":"The same values in different positions are not the same tree."},{"id":"h6","input":{"p":{"__type__":"TreeNode","val":5,"left":{"__type__":"TreeNode","val":3,"left":{"__type__":"TreeNode","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","val":4,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":8,"left":null,"right":null}},"q":{"__type__":"TreeNode","val":5,"left":{"__type__":"TreeNode","val":3,"left":{"__type__":"TreeNode","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","val":4,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":9,"left":null,"right":null}}},"expected":false,"description":"A deeper five-node tree still fails when a lower right value differs."}],"hints":[{"level":1,"content":"Two missing nodes match each other.","revealPattern":false},{"level":2,"content":"If exactly one current node is missing, the structures differ immediately.","revealPattern":true},{"level":3,"content":"After values match, both the left child pair and right child pair must match recursively.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"value-multiset","name":"Compare value counts","summary":"Walk both trees, collect their values into bags, and compare the bags.","decisionReason":"It is fast to write, but a bag forgets where each value sat. Swap a tree's two children and the bag is unchanged while the tree is not, so the bag accepts trees that differ.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":false},{"id":"paired-dfs","name":"Paired recursive DFS","summary":"At each matching position, handle null cases, compare values, then require both child pairs to match.","decisionReason":"At each matching position it accepts two empties, rejects a lone empty, rejects unequal values, then requires both child pairs to match. That mirrors the definition of identical trees and reads structure straight off the nodes.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"both-empty","title":"Accept paired empty nodes","description":"Return true when both current tree nodes are missing.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"accepts_paired_empty_recursive_base_case","scope":"both-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Treating two empty subtrees as a mismatch","Checking values before handling missing nodes"],"hint":"If both nodes are missing, these two subtrees match.","semanticSpec":{"intent":"Handle the base case where both paired nodes are empty.","doneWhen":"This step is done when two missing nodes return true.","shouldFailWhen":"This step should fail if the code rejects two empty subtrees.","roles":["left tree node","right tree node"],"mustProve":["Two missing nodes are accepted."],"mustNotAccept":["Returning false when both nodes are missing."],"proofSnippets":[{"id":"py-both-empty","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True"}],"equivalentVariants":["Use an equivalent paired-empty check such as `p is None and q is None`."]}},{"id":"one-empty","title":"Reject one missing node","description":"Return false when exactly one paired node is missing.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"rejects_missing_recursive_pair_member","scope":"one-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Treating one missing node as a match","Reading values before confirming both nodes exist"],"hint":"After the both-empty case, any remaining missing node means the shapes differ.","semanticSpec":{"intent":"Reject paired tree nodes when one side is missing and the other is present.","doneWhen":"This step is done when a one-sided missing node returns false.","shouldFailWhen":"This step should fail if the code can compare values or recurse with a missing node.","roles":["left tree node","right tree node"],"mustProve":["Exactly one missing node is rejected."],"mustNotAccept":["Treating one empty subtree and one non-empty subtree as equal."],"proofSnippets":[{"id":"py-one-empty","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False"}],"equivalentVariants":["Use an equivalent one-sided missing-node guard after accepting paired empty nodes."]}},{"id":"value-check","title":"Reject value mismatches","description":"Return false when paired existing nodes store different values.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"rejects_paired_node_value_mismatch","scope":"value-check","readMode":"tree-value-query-v1"}]},"commonMistakes":["Comparing only shape and ignoring node values","Recursing before checking the current pair"],"hint":"Once both nodes exist, their values must match before descendants matter.","semanticSpec":{"intent":"Reject paired tree nodes whose current values differ.","doneWhen":"This step is done when a value mismatch returns false before child recursion.","shouldFailWhen":"This step should fail if equal structure with different values can pass.","roles":["left tree node","right tree node","node value"],"mustProve":["Different current values are rejected."],"mustNotAccept":["Ignoring the current node value comparison."],"proofSnippets":[{"id":"py-value-check","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False\n    if p.val != q.val:\n        return False"}],"equivalentVariants":["Use any equivalent comparison of paired node values."]}},{"id":"recurse-pairs","title":"Recurse on both child pairs","description":"Return the conjunction of matching left-child and right-child recursive comparisons.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_paired_child_recursion_conjunction","scope":"recurse-pairs","readMode":"tree-value-query-v1"}]},"commonMistakes":["Checking only one child pair recursively","Using `or` instead of `and` for the child comparisons","Crossing left and right child pairs"],"hint":"Both left children and both right children must match, so combine the recursive calls with `and`.","semanticSpec":{"intent":"Complete the paired-tree comparison by recursively comparing matching child pairs.","doneWhen":"This step is done when both left and right child-pair comparisons must be true.","shouldFailWhen":"This step should fail if one child pair can be ignored or if either recursive result is combined with OR.","roles":["left child pair","right child pair","recursive comparison"],"mustProve":["Both left and right child pairs are recursively compared.","The recursive results are combined with conjunction."],"mustNotAccept":["Recursing on only one child pair.","Combining paired recursive checks with disjunction."],"proofSnippets":[{"id":"py-recurse-pairs","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False\n    if p.val != q.val:\n        return False\n    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)"}],"equivalentVariants":["Use two recursive calls on matching left and right child pairs and require both to pass."]}}],"version":2,"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"When are two trees the same?","workspacePanel":"problem","body":["You get the roots of two binary trees, p and q. Return true only when they are structurally identical and every matching node holds the same value.","Matching values alone are insufficient. The child positions and missing nodes must also agree at every corresponding point in p and q."]},{"id":"pattern-quiz","chapter":"The problem","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which clue decides how to check that two trees are the same?","workspacePanel":"problem","quiz":{"contract":"pattern-recognition-v1","question":"Which clue decides how to check that two trees are the same?","signalPrompt":"p = [1, 2, 3] and q = [1, 3, 2] hold the same three numbers. Which clue decides whether that settles the question?","options":[{"id":"lockstep-positions","label":"Both shape and value have to agree at every matching position, so the two trees must be walked in lockstep","signal":"Sameness is defined position by position, which points at walking both trees together.","rationale":"The definition pins each value to a position, so the check has to visit p and q at the same place at the same time. That is the clue; the exact rule at each position is what we work out next.","isCorrect":true},{"id":"just-values","label":"Only the set of values in each tree has to agree","signal":"Gathering the values looks like it captures each tree.","rationale":"Which values appear is part of the story, but \"the same\" also fixes where each value sits. A clue that ignores position cannot be the deciding one.","isCorrect":false},{"id":"just-counts","label":"Only the height and node count of each tree have to agree","signal":"Matching size feels like a strong structural signal.","rationale":"Two trees can share height and node count yet place different values, or the same values in different spots. Size alone does not decide sameness.","isCorrect":false},{"id":"root-only","label":"Only the two root values have to agree","signal":"The roots are the first thing you can compare.","rationale":"Equal roots clear one position. Everything below the roots still has to match, so the root alone is not the deciding clue.","isCorrect":false}],"missFeedback":"Sameness fixes a value to a position, so the check has to compare p and q at the same place together.","hint":"Ask what \"the same\" forbids: the same values arranged differently. That rules out any clue that ignores position."}},{"id":"brute-force","chapter":"The idea","kind":"info","eyebrow":"A tempting shortcut","title":"A bag of values looks like enough","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bag-p","title":"Bag of p","summary":"p = [1, 2, 3] contributes the values 1, 2, and 3.","state":{"tree":[1,2,3],"visited":[0,1,2]}},{"id":"bag-q","title":"Bag of q","summary":"q = [1, 3, 2] contributes the same three values, so the two bags are equal.","state":{"tree":[1,3,2],"visited":[0,1,2]}}]},"body":["One idea reaches for the easiest thing to collect: gather every value from each tree into a bag and compare the two bags. If the bags hold the same numbers, call the trees the same.","Here p = [1, 2, 3] gives the bag {1, 2, 3}, and q = [1, 3, 2] gives the same bag {1, 2, 3}. The shortcut would answer true from the bag comparison alone."]},{"id":"bag-fails-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Break the shortcut","title":"Are p = [1, 2, 3] and q = [1, 3, 2] the same tree?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,3,2],"swapped":[1,2]}}]},"options":[{"id":"different","label":"No, the children sit on opposite sides","rationale":"The bag of values is identical, but 2 and 3 are swapped. Sameness depends on which value sits at which position, and the bag throws that away.","isCorrect":true},{"id":"same-values","label":"Yes, both trees contain 1, 2, and 3","rationale":"Holding the same values is not enough. The 2 and the 3 must also occupy the same positions, and here they are flipped.","isCorrect":false},{"id":"cannot-tell","label":"There is no way to tell without more values","rationale":"The two three-node trees are fully specified. Reading their positions already tells you they differ.","isCorrect":false}],"answer":"Not the same. Both bags are {1, 2, 3}, yet q swaps the left and right children relative to p. Position carries the answer, so the check has to compare nodes at matching positions.","summary":"The panel shows q = [1, 3, 2]: its highlighted left child holds 3 and its right child holds 2. In p those same positions hold 2 on the left and 3 on the right."},{"id":"local-rule-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"Standing at one matching position, what makes the whole comparison succeed?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":0}}]},"options":[{"id":"values-and-both-children","label":"The values match here, and both child pairs are the same in turn","rationale":"Equal values at this position plus identical left subtrees plus identical right subtrees is exactly what it means for the pair to be the same. Each child pair is the same question one level down.","isCorrect":true},{"id":"values-only","label":"The two values are equal","rationale":"Equal root values is necessary but not sufficient. p = [1, 2, 3] and q = [1, 4, 3] share the root yet differ below it.","isCorrect":false},{"id":"either-child","label":"The values match and at least one child pair matches","rationale":"One matching side is not enough. If the left pair differs, the trees already differ, no matter what the right side does.","isCorrect":false}],"answer":"Same value here, and the left pair is the same, and the right pair is the same. That turns one whole-tree question into the identical question on each child pair, which is what recursion is for.","summary":"Compare p and q at their roots: both hold 1."},{"id":"base-pair-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Anchor the recursion","title":"How does the comparison bottom out past a leaf?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":1,"visited":[0]}}]},"options":[{"id":"both-null-match","label":"Two empty positions match, so this branch reports true","rationale":"Two missing nodes are the same, an empty subtree against an empty subtree. That base case lets a finished branch report success and stops the descent.","isCorrect":true},{"id":"both-null-fail","label":"An empty position cannot be compared, so it fails","rationale":"Half of all child links in a binary tree are empty. Two empties have to count as a match, or no full tree could ever pass.","isCorrect":false},{"id":"one-null-ok","label":"Only one side needs a node for the branch to pass","rationale":"If one side has a node and the other is empty, the shapes already differ. A match needs both present or both empty.","isCorrect":false}],"answer":"Two empty positions are equal, so the branch below this leaf returns true. One present against one empty would be an immediate mismatch. The empty-against-empty case is where each branch finishes.","summary":"The walk sits at the highlighted leaf 2 in each tree and then compares its two empty child positions."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which comparison should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":0}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Trace one matching pair at a time","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":0}}]},"body":["Compare p = [1, 2, 3] against q = [1, 2, 4]. The walk checks the two roots, then steps into each matching child pair in turn.","The panel renders q, the tree on test; p has the same values everywhere except its right child, which holds 3 where q holds 4. Each beat below names p's value at the lit position, so you can compare against the single tree shown."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the comparison","title":"Trace q against p, position by position","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"root-pair","state":{"tree":[1,2,4],"node":0}},{"id":"left-pair","state":{"tree":[1,2,4],"node":1,"visited":[0]}},{"id":"right-pair","state":{"tree":[1,2,4],"node":2,"visited":[0,1]}}]},"beats":[{"id":"root-pair","title":"At the roots, both values are 1. What can the function decide?","summary":"The walk starts at the root of q, lined up against the root of p.","prompt":"q has root value 1, and p has root value 1, so the roots agree.","options":[{"id":"not-yet","label":"No, the child pairs still have to match","rationale":"Equal root values clear this position only. The same tree needs the left pair and the right pair to match too, so the walk descends.","isCorrect":true},{"id":"true-now","label":"Yes, equal roots means the trees are the same","rationale":"A matching root says nothing about the children. p = [1, 2, 3] and q = [1, 4, 3] share the root and still differ.","isCorrect":false},{"id":"false-now","label":"No, and it can already return false","rationale":"Nothing has disagreed yet. The roots match, so the walk keeps going rather than rejecting.","isCorrect":false}],"answer":"Not yet. The roots agree, so the function recurses into the left pair and the right pair before it can commit to an answer."},{"id":"left-pair","title":"The left children are both 2. What does this pair report?","summary":"The walk steps into the left child of q, matched against the left child of p.","prompt":"q's lit left child holds 2, and p holds 2 at that same left position, with both of their children empty.","options":[{"id":"matches","label":"True, the values agree and both child pairs are empty","rationale":"Equal values, and two empty left positions, and two empty right positions. This leaf pair is the same, so it reports true upward.","isCorrect":true},{"id":"pending","label":"Nothing yet, it has to wait for the right side of the tree","rationale":"Each pair resolves on its own. The left pair finishes and reports true independently of what the right pair will do.","isCorrect":false},{"id":"fails","label":"False, a leaf cannot be compared","rationale":"A leaf pair compares fine: equal values and two empty child pairs. It returns true.","isCorrect":false}],"answer":"True. Both hold 2, and each side bottoms out on two empty positions, so the left pair is the same."},{"id":"right-pair","title":"q's right child holds 4. What follows when p holds 3 there?","summary":"The walk steps into the right child of q, the value lit in the panel.","prompt":"The lit right child of q holds 4, while p holds 3 at that same right position.","options":[{"id":"whole-false","label":"This pair returns false, and the whole comparison becomes false","rationale":"The right pair disagrees, so it reports false. The root required both child pairs to match, so one false collapses the entire result to false.","isCorrect":true},{"id":"just-this","label":"Only this branch is false; the tree can still be true","rationale":"The root combines the two child results with and. A single false from either side makes the whole answer false.","isCorrect":false},{"id":"recheck","label":"It descends further to recheck the leaves","rationale":"There is nothing below to rescue a value mismatch. The disagreement at this position is final.","isCorrect":false}],"answer":"False here, and false everywhere. Because the root needs the left pair and the right pair, the mismatched right pair forces the whole comparison to false."}]},{"id":"or-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could one matching side be enough?","summary":"A broken version joins the recursive child results with or: return left-pair matches or right-pair matches. Trees that are truly identical still pass. Watch it on q = [1, 9, 3] against p = [1, 2, 3], where one child pair agrees and the other does not.","workspacePanel":"trace","pitfall":"The code below combines the two recursive child comparisons with or instead of and.","whyItMatters":"The same tree requires the left pair and the right pair to both match, so the two recursive results must be joined with and. Joining them with or lets a single agreeing side mask a mismatch on the other.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def isSame(p: TreeNode | None, q: TreeNode | None) -> bool:\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False\n    if p.val != q.val:\n        return False\n    left_ok = isSame(p.left, q.left)\n    right_ok = isSame(p.right, q.right)\n    return left_ok or right_ok","steps":[{"id":"left-mismatch","title":"The left pair disagrees","codeLine":8,"summary":"q has 9 on the left where p has 2. The left pair reports false.","state":{"tree":[1,9,3],"node":1,"swapped":[1]}},{"id":"right-match","title":"The right pair agrees","codeLine":9,"summary":"q and p both hold 3 on the right. The right pair reports true.","state":{"tree":[1,9,3],"node":2,"visited":[1],"swapped":[2]}},{"id":"or-accepts","title":"or accepts the mismatch","codeLine":10,"summary":"false or true is true, so the code calls these trees the same even though the left children differ.","state":{"tree":[1,9,3],"node":0,"visited":[1,2]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (p == null && q == null) {\n    return true;\n}\nif (p == null || q == null) {\n    return false;\n}\nif (p.val != q.val) {\n    return false;\n}\nconst leftOk = isSame(p.left, q.left);\nconst rightOk = isSame(p.right, q.right);\nreturn (leftOk || rightOk);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10,"9":11,"10":12},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (p == null && q == null) {\n    return true;\n}\nif (p == null || q == null) {\n    return false;\n}\nif (p.val != q.val) {\n    return false;\n}\nconst leftOk = isSame(p.left, q.left);\nconst rightOk = isSame(p.right, q.right);\nreturn (leftOk || rightOk);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10,"9":11,"10":12},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (p == null && q == null) {\n    return true;\n}\nif (p == null || q == null) {\n    return false;\n}\nif (p.val != q.val) {\n    return false;\n}\nboolean leftOk = isSame(p.left, q.left);\nboolean rightOk = isSame(p.right, q.right);\nreturn (leftOk || rightOk);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10,"9":11,"10":12},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (p == null && q == null) {\n    return true;\n}\nif (p == null || q == null) {\n    return false;\n}\nif (p.val != q.val) {\n    return false;\n}\nbool leftOk = IsSame(p.left, q.left);\nbool rightOk = IsSame(p.right, q.right);\nreturn leftOk || rightOk;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10,"9":11,"10":12},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if ((!p && !q)) {\n    return true;\n}\nif ((!p || !q)) {\n    return false;\n}\nif (p->val != q->val) {\n    return false;\n}\nbool left_ok = is_same(p->left, q->left);\nbool right_ok = is_same(p->right, q->right);\nreturn (left_ok || right_ok);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10,"9":11,"10":12},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":0}}]},"body":["Comparing equal values and then both child pairs held for a full tree. A paired walk like this slips where one side runs out of nodes before the other, or where there is nothing to compare at all.","Worth checking before coding: two empty trees with no nodes anywhere, and a pair where one tree has a node exactly where the other has an empty position."]},{"id":"both-empty-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"Are two empty trees the same?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"p":"null","q":"null"}}]},"options":[{"id":"true-empty","label":"True, the comparison succeeds with no work","rationale":"Two empty trees are trivially identical. The both-empty base case fires immediately and returns true, which is also what every finished branch relies on.","isCorrect":true},{"id":"false-empty","label":"False, there is nothing to confirm a match","rationale":"Nothing to compare is the cleanest possible match. Both sides are empty, so they are the same.","isCorrect":false},{"id":"error-empty","label":"It errors, because there are no values to read","rationale":"The both-empty check runs before any value is read, so no field access happens. That ordering is exactly why the base case comes first.","isCorrect":false}],"answer":"True. Two empty trees match, and the both-empty case answers before any value is touched. The same line that ends each branch handles the empty input.","summary":"Both p and q are empty: there is no root on either side."},{"id":"one-empty-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"One tree has a node where the other is empty. What happens?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,null],"node":1}}]},"options":[{"id":"reject-now","label":"It returns false right away, before any value is read","rationale":"One present and one empty means the shapes already differ. The one-empty guard rejects the pair before it could try to read a value from the missing side.","isCorrect":true},{"id":"compare-values","label":"It compares the present value against an empty one","rationale":"There is no value on the empty side to compare. The one-empty guard rejects the pair before any value access is attempted.","isCorrect":false},{"id":"descend","label":"It descends to compare the children of the present node","rationale":"A shape mismatch at this position is already decisive. There is no reason to descend below it.","isCorrect":false}],"answer":"False immediately. After the both-empty case, any remaining empty on exactly one side is a shape mismatch, caught before a missing field is ever read.","summary":"The panel shows p with the highlighted node holding 2 at this position, while q has nothing at the matching position."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The two empty checks have to come before any value read, and the two child pairs join with and.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[1,2,3],"node":0}}]},"body":["At each paired position, accept two empties, reject a lone empty, then reject unequal values. Only after those guards do you trust recursion on the two matching child pairs.","Require both child pairs to match, joining their results so that either mismatch fails the whole comparison."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the parallel comparison","eyebrow":"Code the rule","summary":"Implement the comparison in order: paired empties, lone empties, unequal values, then both child pairs.","workspacePanel":"code","checkpoints":[{"id":"both-empty","title":"Accept paired empty nodes","description":"Return true when both current tree nodes are missing.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"accepts_paired_empty_recursive_base_case","scope":"both-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Treating two empty subtrees as a mismatch","Checking values before handling missing nodes"],"hint":"If both nodes are missing, these two subtrees match.","semanticSpec":{"intent":"Handle the base case where both paired nodes are empty.","doneWhen":"This step is done when two missing nodes return true.","shouldFailWhen":"This step should fail if the code rejects two empty subtrees.","roles":["left tree node","right tree node"],"mustProve":["Two missing nodes are accepted."],"mustNotAccept":["Returning false when both nodes are missing."],"proofSnippets":[{"id":"py-both-empty","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True"}],"equivalentVariants":["Use an equivalent paired-empty check such as `p is None and q is None`."]}},{"id":"one-empty","title":"Reject one missing node","description":"Return false when exactly one paired node is missing.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"rejects_missing_recursive_pair_member","scope":"one-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Treating one missing node as a match","Reading values before confirming both nodes exist"],"hint":"After the both-empty case, any remaining missing node means the shapes differ.","semanticSpec":{"intent":"Reject paired tree nodes when one side is missing and the other is present.","doneWhen":"This step is done when a one-sided missing node returns false.","shouldFailWhen":"This step should fail if the code can compare values or recurse with a missing node.","roles":["left tree node","right tree node"],"mustProve":["Exactly one missing node is rejected."],"mustNotAccept":["Treating one empty subtree and one non-empty subtree as equal."],"proofSnippets":[{"id":"py-one-empty","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False"}],"equivalentVariants":["Use an equivalent one-sided missing-node guard after accepting paired empty nodes."]}},{"id":"value-check","title":"Reject value mismatches","description":"Return false when paired existing nodes store different values.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"rejects_paired_node_value_mismatch","scope":"value-check","readMode":"tree-value-query-v1"}]},"commonMistakes":["Comparing only shape and ignoring node values","Recursing before checking the current pair"],"hint":"Once both nodes exist, their values must match before descendants matter.","semanticSpec":{"intent":"Reject paired tree nodes whose current values differ.","doneWhen":"This step is done when a value mismatch returns false before child recursion.","shouldFailWhen":"This step should fail if equal structure with different values can pass.","roles":["left tree node","right tree node","node value"],"mustProve":["Different current values are rejected."],"mustNotAccept":["Ignoring the current node value comparison."],"proofSnippets":[{"id":"py-value-check","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False\n    if p.val != q.val:\n        return False"}],"equivalentVariants":["Use any equivalent comparison of paired node values."]}},{"id":"recurse-pairs","title":"Recurse on both child pairs","description":"Return the conjunction of matching left-child and right-child recursive comparisons.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_paired_child_recursion_conjunction","scope":"recurse-pairs","readMode":"tree-value-query-v1"}]},"commonMistakes":["Checking only one child pair recursively","Using `or` instead of `and` for the child comparisons","Crossing left and right child pairs"],"hint":"Both left children and both right children must match, so combine the recursive calls with `and`.","semanticSpec":{"intent":"Complete the paired-tree comparison by recursively comparing matching child pairs.","doneWhen":"This step is done when both left and right child-pair comparisons must be true.","shouldFailWhen":"This step should fail if one child pair can be ignored or if either recursive result is combined with OR.","roles":["left child pair","right child pair","recursive comparison"],"mustProve":["Both left and right child pairs are recursively compared.","The recursive results are combined with conjunction."],"mustNotAccept":["Recursing on only one child pair.","Combining paired recursive checks with disjunction."],"proofSnippets":[{"id":"py-recurse-pairs","language":"python","code":"def isSameTree(p, q):\n    if not p and not q:\n        return True\n    if not p or not q:\n        return False\n    if p.val != q.val:\n        return False\n    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)"}],"equivalentVariants":["Use two recursive calls on matching left and right child pairs and require both to pass."]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Two trees are the same when every matching position agrees on value and shape.","workspacePanel":"code","body":["Whole-tree sameness decomposes into one local rule applied at every matching position, then trusted recursively on each child pair.","The ordering of the guards matters: the empty checks run before any value read, so a missing node never gets dereferenced."],"takeaways":[{"title":"Position carries the answer","body":"Matching value bags are not enough; a value has to sit at the same position in both trees, which is why the check compares nodes in lockstep."},{"title":"Guards before reads","body":"Accept two empties, reject a lone empty, then compare values. That order keeps the walk from reading a field off a missing node."},{"title":"Both pairs, joined with and","body":"The left pair and the right pair must both match, so one disagreement anywhere collapses the whole comparison to false."}]}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
