Invert Binary Tree
Invert Binary Tree
Last updated
Last updated
// O(n) time | O(n) space
function invertBinaryTree(tree) {
const queue = [tree];
while (queue.length) {
const current= queue.shift();
if (current === null) continue;
swapLeftAndRight(current);
queue.push(current.left);
queue.push(current.right);
}
}
function swapLeftAndRight(tree) {
const temp = tree.left;
tree.left = tree.right;
tree.right = temp;
}
// This is the class of the input binary tree.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Do not edit the line below.
exports.invertBinaryTree = invertBinaryTree;
// O(n) time | O(n) space
function invertBinaryTree(tree) {
if (tree === null) return;
swapLeftAndRight(tree);
invertBinaryTree(tree.left);
invertBinaryTree(tree.right);
}
function swapLeftAndRight(tree) {
const temp = tree.left;
tree.left = tree.right;
tree.right = temp;
}
// This is the class of the input binary tree.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Do not edit the line below.
exports.invertBinaryTree = invertBinaryTree;