AceYourInterviews
Checking sign-in…

78. Invert Binary Tree

CoreSwap ownership of the two child edges at every identity

Mirror the tree by swapping every node's left and right subtrees. The transformation applies recursively at all depths, not just at the root.

Preserve existing node objects and values according to the mutation contract. Return the root of the transformed tree.

Example 1

Input

[4,2,7,1,3,6,9]

Output

same root; [4,7,2,9,6,3,1]

Explanation: Swap at every node, not only at the root.

Example 2

Input

[1,1,null,1]

Output

same root; [1,null,1,null,1]

Explanation: Duplicate values do not identify nodes; each original edge has an exact mirror destination.

Constraints

  • 0 <= node count per tree <= 105
  • -231 <= node.value <= 231 - 1
  • Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1

What two references belong to one local swap?

Hint 2

Save one child before overwriting either link.

Hint 3

Use an explicit stack, swap once per node, and push both nonnull new children.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Mirror each original identity

[4,2,7,1,3,6,9]
"T0"