albertonline· portal
blind75

Solving Invert Binary Tree: Flipping a Binary Tree

Jan 15, 2024 · Exploring the solution to invert a binary tree, effectively flipping it around its center.

The "Invert Binary Tree" problem focuses on inverting a binary tree, effectively flipping it around its center, such that each left child becomes a right child and vice versa.

Problem Statement

Given the root of a binary tree, invert the tree, and return its root.

Example

Consider a binary tree: Binary Tree

The inverted tree is a mirror image of the original tree.

Solution Approach - Recursive Swap

typescript

Breaking Down the Solution


  • Recursive Approach: The function invertTree is a recursive solution that inverts each node in the tree.
  • Swapping Children: At each node, swap its left and right children.
  • Base Case: If a node is null, return null.

Conclusion


Inverting a binary tree is an interesting problem that demonstrates the elegance and simplicity of recursive tree manipulation, showcasing fundamental concepts in binary tree algorithms.

Rust Solution

rust

Rust models each node as Option<Rc<RefCell<TreeNode>>> because rewiring a child while other handles still point at it needs shared ownership (Rc) plus interior mutability (RefCell). The let node = root?; line leans on ? over the Option to short-circuit to None for the empty-tree base case, standing in for TS's explicit null check. Reading the children goes through node.borrow() and .clone() — a cheap Rc refcount bump, not a deep copy — because you can't move a field out of a borrow, while writing the swapped subtrees back takes a separate node.borrow_mut(), the two runtime-checked borrows RefCell enforces. The recursion then hands the same handle straight back as Some(node).

Go Solution

go

Go's tuple assignment root.Left, root.Right = invertTree(root.Right), invertTree(root.Left) evaluates the whole right-hand side before binding either field, so it swaps the inverted subtrees in one line with no temporary — the same trick as the TS array destructuring. Because nodes are plain *TreeNode pointers, the recursion mutates the fields in place with no interior-mutability wrapper, unlike Rust's RefCell borrow dance. The base case is the idiomatic if root == nil { return nil }.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.