{"id":"invert-binary-tree","title":"Invert Binary Tree","difficulty":"easy","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-basics","concepts":["tree-dfs-basics"],"problemForm":"intro","companies":[],"category":"trees-graphs","compareMode":"exact","description":"Given the root of a binary tree, invert the tree by swapping every node's left and right children, then return the root of the inverted tree.","examples":[{"input":"root = [4,2,7,1,3,6,9]","output":"[4,7,2,9,6,3,1]","explanation":"Every node swaps its left and right child pointers."},{"input":"root = [2,1,3]","output":"[2,3,1]","explanation":"The root stays in place while its two children switch sides."},{"input":"root = []","output":"[]","explanation":"An empty tree stays empty."}],"constraints":[{"id":"0-number-of-nodes-100","text":"0 <= number of nodes <= 100","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":100}},{"id":"100-node-val-100","text":"-100 <= Node.val <= 100","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-100,"max":100}},{"id":"the-returned-tree-may-reuse-the-original-nodes","text":"The returned tree may reuse the original nodes"}],"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 invertTree(self, root: TreeNode | None) -> TreeNode | None:\n        # Your code here\n        pass","functionName":"invertTree","testCases":[{"id":"1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":4,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-3","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":3,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-2","val":7,"left":{"__type__":"TreeNode","__id__":"tree-5","val":6,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-6","val":9,"left":null,"right":null}}}},"expected":{"__type__":"TreeNode","val":4,"left":{"__type__":"TreeNode","val":7,"left":{"__type__":"TreeNode","val":9,"left":null,"right":null},"right":{"__type__":"TreeNode","val":6,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","val":1,"left":null,"right":null}}},"description":"Full tree with two levels of children."},{"id":"2","input":{"root":{"__type__":"TreeNode","__id__":"tree-10","val":2,"left":{"__type__":"TreeNode","__id__":"tree-11","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-12","val":3,"left":null,"right":null}}},"expected":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","val":1,"left":null,"right":null}},"description":"Small balanced tree."},{"id":"3","input":{"root":null},"expected":null,"description":"Empty tree."},{"id":"4","input":{"root":{"__type__":"TreeNode","__id__":"tree-20","val":1,"left":{"__type__":"TreeNode","__id__":"tree-21","val":2,"left":{"__type__":"TreeNode","__id__":"tree-22","val":3,"left":null,"right":null},"right":null},"right":null}},"expected":{"__type__":"TreeNode","val":1,"left":null,"right":{"__type__":"TreeNode","val":2,"left":null,"right":{"__type__":"TreeNode","val":3,"left":null,"right":null}}},"description":"Left-skewed tree becomes right-skewed."},{"id":"h1","input":{"root":{"__type__":"TreeNode","__id__":"tree-h1-0","val":1,"left":null,"right":null}},"expected":{"__type__":"TreeNode","val":1,"left":null,"right":null},"description":"A single node inverts to itself."},{"id":"h2","input":{"root":{"__type__":"TreeNode","__id__":"tree-h2-0","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h2-1","val":1,"left":null,"right":null},"right":null}},"expected":{"__type__":"TreeNode","val":2,"left":null,"right":{"__type__":"TreeNode","val":1,"left":null,"right":null}},"description":"A left child moves to the right."},{"id":"h3","input":{"root":{"__type__":"TreeNode","__id__":"tree-h3-0","val":2,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h3-1","val":3,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h3-2","val":4,"left":null,"right":null}}}},"expected":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":{"__type__":"TreeNode","val":4,"left":null,"right":null},"right":null},"right":null},"description":"A right-skewed tree becomes left-skewed."},{"id":"h4","input":{"root":{"__type__":"TreeNode","__id__":"tree-h4-0","val":4,"left":{"__type__":"TreeNode","__id__":"tree-h4-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h4-2","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h4-3","val":3,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-h4-4","val":7,"left":{"__type__":"TreeNode","__id__":"tree-h4-5","val":6,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h4-6","val":9,"left":null,"right":null}}}},"expected":{"__type__":"TreeNode","val":4,"left":{"__type__":"TreeNode","val":7,"left":{"__type__":"TreeNode","val":9,"left":null,"right":null},"right":{"__type__":"TreeNode","val":6,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","val":1,"left":null,"right":null}}},"description":"A full tree mirrors both subtrees."},{"id":"h5","input":{"root":{"__type__":"TreeNode","__id__":"tree-h5-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-h5-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h5-2","val":4,"left":null,"right":null},"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h5-3","val":3,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h5-4","val":5,"left":null,"right":null}}}},"expected":{"__type__":"TreeNode","val":1,"left":{"__type__":"TreeNode","val":3,"left":{"__type__":"TreeNode","val":5,"left":null,"right":null},"right":null},"right":{"__type__":"TreeNode","val":2,"left":null,"right":{"__type__":"TreeNode","val":4,"left":null,"right":null}}},"description":"Mixed-depth children swap sides recursively."},{"id":"h6","input":{"root":{"__type__":"TreeNode","__id__":"tree-h6-0","val":8,"left":{"__type__":"TreeNode","__id__":"tree-h6-1","val":4,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h6-2","val":6,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-h6-3","val":10,"left":{"__type__":"TreeNode","__id__":"tree-h6-4","val":9,"left":null,"right":null},"right":null}}},"expected":{"__type__":"TreeNode","val":8,"left":{"__type__":"TreeNode","val":10,"left":null,"right":{"__type__":"TreeNode","val":9,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":4,"left":{"__type__":"TreeNode","val":6,"left":null,"right":null},"right":null}},"description":"A missing child on each side still mirrors cleanly."},{"id":"invert-signed-values","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-2,"left":{"__type__":"TreeNode","val":-3,"left":null,"right":null},"right":null},"right":{"__type__":"TreeNode","val":4,"left":{"__type__":"TreeNode","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","val":-1,"left":null,"right":null}}}},"expected":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":4,"left":{"__type__":"TreeNode","val":-1,"left":null,"right":null},"right":{"__type__":"TreeNode","val":1,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":-2,"left":null,"right":{"__type__":"TreeNode","val":-3,"left":null,"right":null}}},"description":"Inversion swaps structure while preserving zero and negative node values."}],"hints":[{"level":1,"content":"The root itself does not move; only child links swap.","revealPattern":false},{"level":2,"content":"After swapping one node's children, both subtrees still need the same inversion.","revealPattern":true},{"level":3,"content":"A recursive DFS can `return` the current node after wiring its children to inverted subtrees.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"How should the function reach every node of the tree?","decisionPrompt":"Weigh the memory each approach needs beyond the nodes it is given.","approaches":[{"id":"rebuild-by-levels","name":"Build a second, mirrored tree","summary":"Walk the given tree level by level and create a new node for each one, hung on the opposite side.","decisionReason":"It returns a correct mirror image, but it creates a new node for every node it is given and holds a queue of nodes while it walks. The given nodes can be reused by changing two links on each.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) extra space for the new nodes."],"isOptimal":false},{"id":"recursive-swap","name":"Recursive swap on the given nodes","summary":"Call the function on each child, hang the two returned subtrees on opposite sides, and return the node.","decisionReason":"Each call changes only its own node's two links and creates no nodes. The extra memory is the stack of waiting calls, one per level of the tree.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space for the waiting calls."],"isOptimal":true}]},"codingCheckpoints":[{"id":"recursive-base-and-children","title":"Return an empty tree as it is","description":"When the function is handed an empty tree, return it before reading a left or right link.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"guards_empty_recursive_base_case","scope":"return-empty-subtree","readMode":"tree-value-query-v1"}]},"commonMistakes":["Reading a child link before checking that there is a node","Returning a new node in place of the empty tree"],"hint":"An empty tree is its own mirror image, and it has no links to read.","semanticSpec":{"intent":"Return an empty subtree before accessing either child link.","doneWhen":"This step is done when a missing root returns unchanged.","shouldFailWhen":"This step should fail if the empty-root guard or its return is absent.","roles":["current root","empty subtree"],"mustProve":["A missing root is returned before child access."],"mustNotAccept":["Dereferencing a missing root."],"proofSnippets":[{"id":"py-empty-base-case","language":"python","code":"def invertTree(root):\n    if not root:\n        return None"}],"equivalentVariants":[]}},{"id":"recurse-children","title":"Invert both child subtrees","description":"Call the function on the left child and on the right child, and keep both results before either link changes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"recurses_into_child_subtrees","scope":"recursive-step","readMode":"tree-value-query-v1"}]},"commonMistakes":["Calling the function on only one child","Writing the first result into a link, then making the second call through that same link"],"hint":"Both calls need to start from the original children.","semanticSpec":{"intent":"Recursively invert both original child subtrees before the current root is rewired.","doneWhen":"This step is done when the function recurses into both the left and right child subtrees.","shouldFailWhen":"This step should fail if either child recursion is missing or both calls use the same child.","roles":["current root","left child","right child","recursive call"],"mustProve":["The left child subtree is recursively processed.","The right child subtree is recursively processed."],"mustNotAccept":["Only inverting one child subtree.","Recursing into the same child twice."],"proofSnippets":[{"id":"py-recurse-children","language":"python","code":"def invertTree(root):\n    if not root:\n        return None\n    left = invertTree(root.left)\n    right = invertTree(root.right)"}],"equivalentVariants":[]}},{"id":"swap-links","title":"Hang the results on opposite sides","description":"Point the left link at the inverted right subtree and the right link at the inverted left subtree.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"swaps_recursive_child_links","scope":"swap-links","readMode":"tree-value-query-v1"}]},"commonMistakes":["Hanging each result back on the side it came from","Trading the two children's values and leaving the links as they were"],"hint":"On the 7-node tree, node 4 ends with 7 on its left and 2 on its right.","semanticSpec":{"intent":"Assign each child link from the recursively inverted opposite child result.","doneWhen":"The current root's left link receives the original right subtree result and its right link receives the original left subtree result.","shouldFailWhen":"The code only recurses without rewiring, assigns both sides from the same result, or writes a child before preserving the opposite side.","roles":["current root","left child result","right child result"],"mustProve":["opposite child-link assignment"],"mustNotAccept":["same-side child reassignment"],"proofSnippets":[{"id":"py-swap-links","language":"python","code":"def invertTree(root):\n    if not root:\n        return None\n    left = invertTree(root.left)\n    right = invertTree(root.right)\n    root.left = right\n    root.right = left"}]}},{"id":"return-root","title":"Return the node itself","description":"After its two links are swapped, return the node as the root of its inverted subtree.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_current_tree_root","scope":"return-root","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning one of the children","Returning nothing after the swap"],"hint":"The caller hangs whatever comes back, so it has to be the root of this subtree.","semanticSpec":{"intent":"Return the same current root after its child links have been rewired.","doneWhen":"The recursive function returns the current root pointer as the subtree result.","shouldFailWhen":"The code returns a child, a traversal collection, or nothing after rewiring.","roles":["current root","subtree result"],"mustProve":["current root return"],"mustNotAccept":["returning one child subtree"],"proofSnippets":[{"id":"py-return-root","language":"python","code":"def invertTree(root):\n    if not root:\n        return None\n    left = invertTree(root.left)\n    right = invertTree(root.right)\n    root.left = right\n    root.right = left\n    return root"}]}}],"version":2,"progressRevision":"invert-binary-tree-2026-11-20-earned-recursion","slides":[{"id":"the-task","kind":"info","title":"Invert a binary tree","workspacePanel":"problem","body":["You are given the root of a binary tree, the node at the top. Return the root of the inverted tree, which is the same tree seen in a mirror: whatever was on the left is on the right, at every level.","Each node has a left link and a right link to its children. A node with no children, like 1, is called a leaf.","Inverting keeps every node, every value and every parent. It changes only which side each child hangs on."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"given","title":"The tree you are given","summary":"4 is the root, with 2 on its left and 7 on its right. The bottom row reads 1, 3, 6, 9.","state":{"tree":[4,2,7,1,3,6,9]}},{"id":"inverted","title":"The tree to return","summary":"4 is still the root, now with 7 on its left and 2 on its right. The bottom row reads 9, 6, 3, 1.","state":{"tree":[4,7,2,9,6,3,1]}}]}},{"id":"root-swap-only","kind":"case-probe","title":"Suppose you start at the top, and node 4's two children trade places. What is left to do?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"root-swapped","state":{"tree":[4,7,2,6,9,1,3],"node":0}}]},"options":[{"id":"invert-both-subtrees","label":"Invert the smaller trees rooted at 7 and at 2","rationale":"Under 7, the 6 still hangs left of the 9, and under 2 the 1 still hangs left of the 3. Each of those smaller trees, called a subtree, needs the same inverting, on fewer nodes. The function you are writing inverts any tree, so it can do both jobs by calling itself, once on 7 and once on 2.","isCorrect":true},{"id":"already-inverted","label":"Nothing: the two sides have traded places","rationale":"The mirror image reads 9, 6, 3, 1 along the bottom row. This tree reads 6, 9, 1, 3.","isCorrect":false},{"id":"trade-bottom-row","label":"Trade 6 with 1 and 9 with 3 along the bottom row","rationale":"That would hang 1 and 3 under 7. In the mirror image 7 keeps its own children, 6 and 9, with their sides switched.","isCorrect":false}]},{"id":"recursion-contract","kind":"case-probe","title":"Back on the given tree, the function has called itself on node 2, and that call has just finished. What did it return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-call-finished","state":{"tree":[4,2,7,3,1,6,9],"node":0,"visited":[1,3,4]}}]},"options":[{"id":"node-two-inverted","label":"Node 2, with everything under it inverted","rationale":"The function returns the root of the inverted tree. It was handed the tree rooted at 2, and after inverting, that tree's root is still 2. So the call on node 4 gets back a finished subtree and never has to look inside it.","isCorrect":true},{"id":"node-three","label":"Node 3, which now hangs on 2's left","rationale":"3 changed sides, but it is still a child of 2. The root of this subtree is the node the call was handed.","isCorrect":false},{"id":"whole-tree-root","label":"Node 4, the root of the whole tree","rationale":"This call was handed node 2 and follows links downward only. Nothing it can reach leads back up to 4.","isCorrect":false}]},{"id":"attach-opposite-sides","kind":"case-probe","title":"The calls on 2 and on 7 have both returned. What does the call on node 4 do with the two results?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"both-calls-finished","state":{"tree":[4,2,7,3,1,9,6],"node":0,"visited":[1,2,3,4,5,6]}}]},"options":[{"id":"opposite-sides","label":"Hang 7 on its left and 2 on its right","rationale":"Both subtrees are already inverted inside. The only thing still on the wrong side is each subtree as a whole. So the whole job at any node is to invert both subtrees, hang the results on opposite sides, and return the node.","isCorrect":true},{"id":"same-sides","label":"Hang 2 on its left and 7 on its right","rationale":"That is where they already hang. The bottom row would stay 3, 1, 9, 6: each pair reversed, with the pairs in their old order.","isCorrect":false},{"id":"trade-values","label":"Trade the values 2 and 7 and leave the links alone","rationale":"The node now holding 7 would have 3 and 1 under it. Children stay with their parent in a mirror image, so the links have to change.","isCorrect":false}]},{"id":"base-case-probe","kind":"case-probe","title":"The call on leaf 1 still makes a call on its left child, and there is nothing there: an empty tree. What should that call return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"at-leaf-one","state":{"tree":[4,2,7,1,3,6,9],"node":3}}]},"options":[{"id":"empty-unchanged","label":"The empty tree, unchanged","rationale":"A tree with no nodes is its own mirror image, so the call returns it as it is. The function checks for an empty tree before anything else, because an empty tree has no left or right link to read.","isCorrect":true},{"id":"the-leaf","label":"Leaf 1, the nearest node","rationale":"The call on 1 would then hang node 1 under itself, as its own child.","isCorrect":false},{"id":"new-node","label":"A new node to fill the gap","rationale":"The mirror image has the same 7 nodes as the given tree. A new node under 1 would make an eighth.","isCorrect":false}]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"One full run on the given tree","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start","state":{"tree":[4,2,7,1,3,6,9],"node":0}},{"id":"leaf-one-swaps","state":{"tree":[4,2,7,1,3,6,9],"node":3}},{"id":"node-two-swaps","state":{"tree":[4,2,7,3,1,6,9],"node":1,"visited":[3,4]}},{"id":"right-call-returns","state":{"tree":[4,2,7,3,1,9,6],"node":0,"visited":[1,2,3,4,5,6]}},{"id":"root-swaps","state":{"tree":[4,7,2,9,6,3,1],"visited":[0,1,2,3,4,5,6]}}]},"beats":[{"id":"first-swap","title":"The function is called on node 4, and it calls itself on the left child first. Which node is the first to swap its two links?","options":[{"id":"node-one","label":"Node 1","rationale":"The call on 4 makes its call on 2 before it touches a link, and the call on 2 does the same with 1. Leaf 1's two calls come straight back empty, so its call is the first to have both results. Swapping two empty links leaves the drawing as it was.","isCorrect":true},{"id":"node-four","label":"Node 4","rationale":"The call on 4 starts first, but it changes no link until both of its own calls have returned. It swaps last.","isCorrect":false},{"id":"node-two","label":"Node 2","rationale":"The call on 2 is still waiting for its calls on 1 and on 3.","isCorrect":false}]},{"id":"node-two","title":"Leaf 1 returns, leaf 3 does the same, and node 2 swaps its two links. What does that change?","options":[{"id":"three-left-one-right","label":"3 now hangs left of 2, and 1 hangs right","rationale":"The call on 2 hangs the result of its left call, node 1, on the right, and the result of its right call, node 3, on the left.","isCorrect":true},{"id":"nothing-until-root","label":"Nothing visible: 1 and 3 trade places later, when node 4 swaps","rationale":"The swap at 4 moves the whole subtree under 2 across in one piece. The order of 2's own children changes only at node 2.","isCorrect":false},{"id":"two-moves","label":"2 moves to the right of 4, taking 1 and 3 with it","rationale":"Which side 2 hangs on is one of node 4's links. The swap at 2 changes only 2's own two links.","isCorrect":false}]},{"id":"right-call","title":"Node 2 returns, and node 4 makes its right call, on 7. How does the bottom row read when that call returns?","options":[{"id":"right-pair-reversed","label":"3, 1, 9, 6","rationale":"The call on 7 swaps 6 and 9 the way the call on 2 swapped 1 and 3. Node 4 has not swapped yet, so the left pair is still on the left.","isCorrect":true},{"id":"fully-mirrored","label":"9, 6, 3, 1","rationale":"That is the finished mirror image. It needs the swap at node 4, and the call on 4 is still waiting for this result.","isCorrect":false},{"id":"right-pair-untouched","label":"3, 1, 6, 9","rationale":"The call on 7 does not stop at 7. It makes its own two calls, on 6 and on 9, and then swaps them.","isCorrect":false}]},{"id":"swap-count","title":"Node 4 swaps its two links and the run is over. How many of the 7 nodes swapped their links along the way?","options":[{"id":"all-seven","label":"7: every node, leaves included","rationale":"Each node is the root of exactly one call, and every call on a node makes one swap. The four leaves each swapped two empty links. So the work grows in step with the number of nodes.","isCorrect":true},{"id":"three-parents","label":"3: nodes 2, 7 and 4","rationale":"Those are the swaps that changed the drawing. Leaves 1, 3, 6 and 9 ran the same swap on two empty links.","isCorrect":false},{"id":"root-only","label":"1: node 4, whose swap moved both subtrees","rationale":"The swap at 4 moved the two subtrees across. The order inside each one came from the swaps at 2 and 7.","isCorrect":false}]}]},{"id":"hold-both-results","kind":"info","title":"In that run, the call on node 4 kept both results before it changed a link.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"given-again","state":{"tree":[4,2,7,1,3,6,9]}}]},"body":["A shorter version keeps nothing. It makes the first call and puts the result straight into a link. Then it makes the second call and puts that result into the other link.","Both versions make two calls and set two links. Only the order of those four steps is different."]},{"id":"overwrite-pitfall","kind":"pitfall","title":"Can each result go straight into a link?","summary":"The first line after the empty check calls the function on the right child. So from node 4, the run goes to 7 and then to 9 before any link changes.","workspacePanel":"trace","pitfall":"This version writes each result into a link as soon as its call returns.","whyItMatters":"Once the first link changes, nothing leads to the original left child, so the second call cannot start from it. Make both calls while both links still lead to the original children, keep the two results, and change the links last.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def invertTree(root: TreeNode | None) -> TreeNode | None:\n    if not root:\n        return None\n    root.left = invertTree(root.right)\n    root.right = invertTree(root.left)\n    return root","steps":[{"id":"left-link-overwritten","title":"Node 7's left link is overwritten","codeLine":4,"summary":"The call on 9 returns, and its result goes straight into 7's left link. Both of 7's links now lead to 9, and no link leads to 6.","state":{"tree":[4,2,7,1,3,9,9],"node":2}},{"id":"second-call-follows-new-link","title":"The second call follows the new link","codeLine":5,"summary":"This line is meant to invert 7's original left subtree, the 6. It follows 7's left link, which now leads to 9, so the function runs on 9 a second time.","state":{"tree":[4,2,7,1,3,9,9],"node":2}},{"id":"seven-returns","title":"Node 7 returns with 9 on both sides","codeLine":6,"summary":"The call hands node 7 back to the call on 4. No call ever reached 6.","state":{"tree":[4,2,7,1,3,9,9],"node":2}},{"id":"root-repeats","title":"The same thing happens at node 4","codeLine":4,"summary":"The returned 7 goes straight into 4's left link, which cuts off 2 along with 1 and 3. The second call then follows that link to 7 again.","state":{"tree":[4,7,7,9,9,9,9],"node":0}},{"id":"returned-tree","title":"The tree that comes back","codeLine":6,"summary":"Node 4 has the same 7 on both sides, with the same 9 under it twice. No line failed, and 2, 1, 3 and 6 are gone.","state":{"tree":[4,7,7,9,9,9,9],"node":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (root == null) {\n    return null;\n}\nroot.left = invertTree(root.right);\nroot.right = invertTree(root.left);\nreturn root;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6},"statementBundles":{"3":{"startLine":2,"endLine":3}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (root == null) {\n    return null;\n}\nroot.left = invertTree(root.right);\nroot.right = invertTree(root.left);\nreturn root;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6},"statementBundles":{"3":{"startLine":2,"endLine":3}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (root == null) {\n    return null;\n}\nroot.left = invertTree(root.right);\nroot.right = invertTree(root.left);\nreturn root;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6},"statementBundles":{"3":{"startLine":2,"endLine":3}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (root == null) {\n    return null;\n}\nroot.left = InvertTree(root.right);\nroot.right = InvertTree(root.left);\nreturn root;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6},"statementBundles":{"3":{"startLine":2,"endLine":3}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (!root) {\n    return nullptr;\n}\nroot->left = invert_tree(root->right);\nroot->right = invert_tree(root->left);\nreturn root;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6},"statementBundles":{"3":{"startLine":2,"endLine":3}}}}}},{"id":"edge-case-intro","kind":"info","title":"Back to the version that keeps both results. Next, two other trees.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"chain","state":{"tree":[1,2,null,3]}}]},"body":["Every node so far had two children or none. In the first new tree, drawn here, no node has a right child, so the nodes form a chain. The second tree has no nodes at all.","Does the same function handle both?"]},{"id":"chain-probe","kind":"case-probe","title":"In the first tree, no node has a right child. What does the function return for it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"chain-given","state":{"tree":[1,2,null,3]}}]},"options":[{"id":"leans-right","label":"The same chain, leaning right","rationale":"At 1 and at 2, the left call returns a node and the right call returns an empty tree. Hanging them on opposite sides puts the node on the right and the empty tree on the left.","isCorrect":true},{"id":"unchanged","label":"The same tree, unchanged","rationale":"The missing right child still gets a call, and that call returns an empty tree. The swap trades the child with that empty result.","isCorrect":false},{"id":"upside-down","label":"The chain upside down: 3, then 2, then 1","rationale":"Inverting changes which side a child hangs on. It never changes which node is the parent, so 1 stays at the top.","isCorrect":false}]},{"id":"chain-depth","kind":"case-probe","title":"The call on node 3 has just started. How many calls above it are still waiting to finish?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"chain-at-three","state":{"tree":[1,2,null,3],"node":3}}]},"options":[{"id":"two-waiting","label":"2: the calls on 1 and on 2","rationale":"The call on 1 cannot swap until its call on 2 returns, and the call on 2 is waiting on 3 in the same way. Each waiting call holds memory until it returns. On a chain of n nodes, about n calls wait at once.","isCorrect":true},{"id":"one-waiting","label":"1: only the call on 2, which made this one","rationale":"The call on 2 was itself made by the call on 1, and that one has not returned either.","isCorrect":false},{"id":"none-waiting","label":"0: each call finishes before the next one starts","rationale":"A call makes both of its own calls before it swaps, so it cannot finish while one of them is still running.","isCorrect":false}]},{"id":"empty-tree-probe","kind":"case-probe","title":"The second tree has no nodes at all. What does the function do?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-nodes","state":{"nodes":0}}]},"options":[{"id":"returns-empty","label":"Returns the empty tree from its first check","rationale":"The check that ended the calls below every leaf also runs on the very first call. It returns before any link is read. So one check covers an empty input, the missing children of every leaf, and the missing side of a node with one child.","isCorrect":true},{"id":"fails-on-link","label":"Fails when it reads the root's left link","rationale":"It would, if the empty check came after that read. The check is the first thing every call does.","isCorrect":false},{"id":"single-new-node","label":"Returns a single new node as the root","rationale":"The mirror image of no nodes is no nodes, and nothing in the function creates one.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"Each call swaps one node's links. Now write the function.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"given-before-coding","state":{"tree":[4,2,7,1,3,6,9]}}]},"body":["The function is handed one node, the root of a tree. If the tree is empty, it returns it right away.","Otherwise it calls itself on the left child and on the right child, and keeps both results.","Then it points the left link at the right child's result and the right link at the left child's result. Last, it returns the node."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Invert the tree","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"One swap at every node inverts the tree","workspacePanel":"code","takeaways":[{"title":"A call returns a finished subtree","body":"Calling the function on a child hands back that child with everything under it inverted, so each call changes only its own node's two links."},{"title":"Make both calls before changing a link","body":"A result written over a link that the second call still has to follow sends that call down the wrong child. On the 7-node tree that returned 4 with the same 7 on both sides and lost 2, 1, 3 and 6."},{"title":"One empty check handles the edges","body":"Returning an empty tree before reading a link ends the calls below every leaf, and it covers an empty input and a one-child node with no extra code."},{"title":"O(n) time, O(h) space","body":"Each of the n nodes gets one call and one swap, so the time is O(n). The waiting calls stack one per level, so the extra space is O(h) for a tree h levels deep, and a one-sided chain is n levels deep."}]}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
