Editorial solutions and visualizations are prepared with care, but we do not guarantee 100% accuracy or completeness. Please use your own judgment to verify results. Visucodize is not responsible for decisions made based on this content.
Solution code
constCURRENT='current',CURRENT_COLOR='blue';constINVERTED='inverted',INVERTED_COLOR='green';constIN_PROGRESS='in_progress',IN_PROGRESS_COLOR='gray';functionvisMainFunction(treeInput){initClassProperties();explanationAndColorSchemaNotifications();const root =convertInputToTree(treeInput);const tree =newVisBinaryTree(root,{dataPropName:'val'});invertTree(root, tree);notification(`π <b>Done!</b> The binary tree has been successfully inverted.`);return root;}functioninvertTree(node, tree){if(!node){notification(`πΏ Encountered a <code>null</code> node β this marks an empty branch, so thereβs nothing to invert.`);returnnull;}startPartialBatch();setAsCurrentNode(node, tree);notification(`β³ Starting inversion for the ${makeColoredSpan('current node',CURRENT_COLOR)} β marking it as ${makeColoredSpan('in progress',IN_PROGRESS_COLOR)} and beginning with its left subtree.`);
tree.makeVisManagerForNode(node).addClass(IN_PROGRESS);endBatch();// Recurse leftconst left =invertTree(node.left, tree);startPartialBatch();setAsCurrentNode(node, tree);notification(`β Finished inverting the left subtree of the ${makeColoredSpan('current node',CURRENT_COLOR)}. Now moving on to the right subtree.`);endBatch();// Recurse rightinvertTree(node.right, tree);startPartialBatch();setAsCurrentNode(node, tree);notification(`β Both subtrees of the ${makeColoredSpan('current node',CURRENT_COLOR)} are inverted. βοΈ Performing the final step β swapping its left and right children to complete its inversion.`);
tree.preserveNode(left);
node.left = node.right;
node.right = left;
tree.undoPreserveNode(left);
tree.makeVisManagerForNode(node).removeClass(IN_PROGRESS).addClass(INVERTED);notification(`π Swap complete! The ${makeColoredSpan('current node',CURRENT_COLOR)} is now fully ${makeColoredSpan('inverted',INVERTED_COLOR)}.`);endBatch();return node;}let current =null;functionsetAsCurrentNode(node, tree){startBatch();if(current){
tree.makeVisManagerForNode(current).removeClass(CURRENT);}
tree.makeVisManagerForNode(node).addClass(CURRENT);
current = node;endBatch();}functioninitClassProperties(){setClassProperties(CURRENT,{borderColor:CURRENT_COLOR});setClassProperties(INVERTED,{backgroundColor:INVERTED_COLOR});setClassProperties(IN_PROGRESS,{backgroundColor:IN_PROGRESS_COLOR});}functionconvertInputToTree(arr){if(!arr.length || arr[0]===null)returnnull;const nodes = arr.map(val=>(val ===null?null:newTreeNode(val)));for(let i =0; i < arr.length; i++){if(nodes[i]){
nodes[i].left = nodes[2* i +1]||null;
nodes[i].right = nodes[2* i +2]||null;}}return nodes[0];}functionTreeNode(val, left =null, right =null){this.val = val;this.left = left;this.right = right;}functionexplanationAndColorSchemaNotifications(){explanationNotification();notification(`
π¨ <b>Visual Cues:</b>
<ul>
<li>${makeColoredSpan(CURRENT_COLOR+' border',CURRENT_COLOR)} β marks the <b>current node</b> being processed.</li>
<li>${makeColoredSpan(IN_PROGRESS_COLOR+' background',IN_PROGRESS_COLOR)} β indicates a node whose inversion is in progress.</li>
<li>${makeColoredSpan(INVERTED_COLOR+' background',INVERTED_COLOR)} β marks a node whose inversion is completed.</li>
</ul>
`);}
Solution explanation
Solution explanation
Approach
We invert the binary tree using a post-order DFS traversal β process the left subtree first, then the right subtree,
and finally swap the two child pointers of the current node to complete its inversion.
This ensures that before the swap occurs, both of the nodeβs subtrees have already been inverted.
Base case:
If the node is null, it indicates an empty branch β return null immediately since thereβs nothing to invert.
Recursive step (post-order):
Recursively invert the left subtree.
Recursively invert the right subtree.
Swap node.left and node.right after both subtrees have been processed.
Return the current node.
Time Complexity
O(n), where n is the number of nodes β each node is visited exactly once.
Space Complexity
O(h), where h is the height of the tree β recursion stack proportional to the tree height
(O(n) in the worst case for a skewed tree; O(log n) for a balanced tree).
Input-1
Visucodize editorial solution titled JS Solution for LeetCode's Invert Binary Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/invert-binary-tree.