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

class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;

  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function invertTree(root: TreeNode | null): TreeNode | null {
  if (root === null) {
    return null;
  }
  [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
  return root;
}

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.

Comments (0)

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

No comments yet. Be the first.