Mental Model
Flip the tree so left and right children swap places at every node.
Analogy: Imagine holding a tree-shaped mirror and seeing the tree's reflection flipped left to right.
1 / \ 2 3 / \ 4 5
1 / \ 2 3 / \ 4 5
1 / \ 3 2 / \ 5 4
1 / \ 3 2 / \ 5 4
1 / \ 3 2 / \ 5 4
1 / \ 3 2 / \ 5 4
1 / \ 3 2 / \ 5 4
1 / \ 3 2 / \ 5 4
package main import "fmt" // TreeNode defines a node in a binary tree type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // mirrorTree swaps left and right children recursively to mirror the tree func mirrorTree(root *TreeNode) *TreeNode { if root == nil { return nil } // swap left and right children root.Left, root.Right = root.Right, root.Left // recursively mirror left subtree mirrorTree(root.Left) // recursively mirror right subtree mirrorTree(root.Right) return root } // printTree prints the tree in preorder with structure func printTree(root *TreeNode) { if root == nil { return } fmt.Print(root.Val, " ") printTree(root.Left) printTree(root.Right) } func main() { // build tree: 1 // / \ // 2 3 // / \ // 4 5 root := &TreeNode{Val: 1} root.Left = &TreeNode{Val: 2} root.Right = &TreeNode{Val: 3} root.Left.Left = &TreeNode{Val: 4} root.Right.Right = &TreeNode{Val: 5} fmt.Print("Original tree preorder: ") printTree(root) fmt.Println() mirrorTree(root) fmt.Print("Mirrored tree preorder: ") printTree(root) fmt.Println() }
if root == nil { return nil }root.Left, root.Right = root.Right, root.LeftmirrorTree(root.Left)mirrorTree(root.Right)if root == nil { return nil }
if root == nil { return nil }
root.Left, root.Right = root.Right, root.Left