Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Created November 16, 2021 20:00
Show Gist options
  • Save cagataycali/ebd4972b13ffd49aeeb2deabe0a9b3fb to your computer and use it in GitHub Desktop.
Save cagataycali/ebd4972b13ffd49aeeb2deabe0a9b3fb to your computer and use it in GitHub Desktop.
[JavaScript] Invert binary tree
// O(n) time & space
function invertBinaryTree(tree) {
if (tree === null) return;
swapLeftAndRight(tree);
invertBinaryTree(tree.left);
invertBinaryTree(tree.right);
}
function swapLeftAndRight(tree) {
const left = tree.left;
tree.left = tree.right;
tree.right = left;
}
// This is the class of the input binary tree.
function BinaryTree(value) {
this.value = value;
this.left = null;
this.right = null;
}
/*
tree = 1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
*/
const tree = new BinaryTree(1);
tree.left = new BinaryTree(2);
tree.right = new BinaryTree(3);
tree.left.left = new BinaryTree(4);
tree.left.right = new BinaryTree(5);
tree.right.left = new BinaryTree(6);
tree.right.right = new BinaryTree(7);
tree.left.left.left = new BinaryTree(8);
tree.left.left.right = new BinaryTree(9);
invertBinaryTree(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment