DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 55

The task is to invert a binary tree

function invert(node) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

To invert a binary tree means to invert the left and right child of every node. Do this for every node in the binary tree.

If there are no nodes, return null

if(!node) return null;
Enter fullscreen mode Exit fullscreen mode

Store the left child in a temp variable, assign it to the right child and the right child to the left child.

const temp = node.left;
node.left = node.right;
node.right = temp;
Enter fullscreen mode Exit fullscreen mode

Then, invert the left subtree and the right subtree

invert(node.left);
invert(node.right);
Enter fullscreen mode Exit fullscreen mode

The final code

function invert(node) {
  // your code here
  if(!node) return null;

  const temp = node.left
  node.left = node.right
  node.right = temp

  invert(node.left);
  invert(node.right);

  return node;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)