Invert Binary Tree - JS Solution

JS
Editorial

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):
    1. Recursively invert the left subtree.
    2. Recursively invert the right subtree.
    3. Swap node.left and node.right after both subtrees have been processed.
    4. 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).

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.