freeCodeCamp Challenge Guide: Invert a Binary Tree

Invert a Binary Tree


Hints

Hint 1

Create a invert(node = this.root) method in the BinarySearchTree constructor function.

Hint: 2

Try to use recursion and think of a base case.


Solutions

Solution 1 (Click to Show/Hide)
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));

function Node(value) {
  this.value = value;
  this.left  = null;
  this.right = null;
}

function BinarySearchTree() {
  this.root = null;
  // Only change code below this line
  this.invert = function(node = this.root) {
    if (!node) return null;

    [node.left, node.right] = [node.right, node.left];
    this.invert(node.left);
    this.invert(node.right);
  }
  // Only change code above this line
}

Code Explanation

  • Using recursion will allow you to traverse each node once. You keep swapping the left and right pointers of a node until you reach the leaves which will not do anything as the left and right of them are null references.
3 Likes