Skip to content

Invert Binary Tree

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

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

inverted binary tree

Solution

Use a recursive function to invert the tree. The function will swap the left and right child of the current node, and then recursively invert the left and right child nodes.

Implementation

function invertTree(root) {
if (root === null) {
return null;
}
const left = invertTree(root.left);
const right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}

Pseudocode

  1. If the root is null, return null
  2. Recursively invert the left and right child nodes
  3. Swap the left and right child nodes
  4. Return the root node

Complexity Analysis

  • The time complexity of this algorithm is O(N), where N is the number of nodes in the binary tree.
  • The space complexity of this algorithm is O(N), where N is the number of nodes in the binary tree.