📖
Coding interview questions
  • 👋Coding Interview
  • Easy
    • Two number sum
    • Validate Subsequence
    • Sorted Squared Array
    • Tournament Winner
    • Non-Constructible Change
    • Find Closest Value in BTS
    • Branch sum
    • Node Depths
    • Depth-first Search
    • Minimum Waiting Time
    • Class Photos
  • Medium
    • Three Number Sum
    • Smallest Difference
    • Move Element To End
    • Monotonic Array
    • Spiral Traverse
    • Longest Peak
    • Array Of Products
    • First Duplicate Value
    • Merge Overlapping Intervals
    • Zero Sum Subarray
    • BST Traversal
    • Validate BST
    • Min Height BST
    • Find Kth Largest Value In BST
    • Reconstruct BST
    • Invert Binary Tree
  • Hard
    • Three Number Sum
  • Really-Hard
    • Three Number Sum
Powered by GitBook
On this page
  1. Medium

Invert Binary Tree

Invert Binary Tree

Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding right node.

Each BinaryTree node has an integer value, a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null.

Sample Input

tree =    1
       /     \
      2       3
    /   \   /   \
   4     5 6     7
 /   \
8     9

Sample Output

       1
    /     \
   3       2
 /   \   /   \
7     6 5     4
            /   \
           9     8
// O(n) time | O(n) space
function invertBinaryTree(tree) {
  const queue = [tree];
  while (queue.length) {
    const current= queue.shift();
    if (current === null) continue;
    swapLeftAndRight(current);
    queue.push(current.left);
    queue.push(current.right);
  }
}

function swapLeftAndRight(tree) {
  const temp = tree.left;
  tree.left = tree.right;
  tree.right = temp;
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.invertBinaryTree = invertBinaryTree;
// O(n) time | O(n) space
function invertBinaryTree(tree) {
  if (tree === null) return;
  swapLeftAndRight(tree);
  invertBinaryTree(tree.left);
  invertBinaryTree(tree.right);
}

function swapLeftAndRight(tree) {
  const temp = tree.left;
  tree.left = tree.right;
  tree.right = temp;
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.invertBinaryTree = invertBinaryTree;

PreviousReconstruct BSTNextThree Number Sum

Last updated 2 years ago

Page cover image