reverse a binary tree in javascript

To reverse a binary tree, we need to swap the left and right children of every node in the tree. This can be done using a recursive approach where we traverse the tree in a postorder fashion (left node -> right node -> root node).

Here's the code to achieve this:

index.tsx
function reverseTree(root) {
  if (root === null) {
    return;
  }

  // traverse left subtree
  reverseTree(root.left);
  // traverse right subtree
  reverseTree(root.right);

  // swapping left and right nodes
  let temp = root.left;
  root.left = root.right;
  root.right = temp;
}

// Example usage:
// Create a binary tree
//     1
//    / \
//   2   3
//  / \   
// 4   5 
let root = {
  value: 1,
  left: {
    value: 2,
    left: {
      value: 4,
      left: null,
      right: null
    },
    right: {
      value: 5,
      left: null,
      right: null
    }
  },
  right: {
    value: 3,
    left: null,
    right: null
  }
};

// Reverse the tree
reverseTree(root);

// The reversed tree looks like:
//     1
//    / \
//   3   2
//       / \   
//      5   4 
775 chars
55 lines

gistlibby LogSnag