The task is to invert a binary tree
function invert(node) {
// your code here
}
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;
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;
Then, invert the left subtree and the right subtree
invert(node.left);
invert(node.right);
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;
}
That's all folks!
Top comments (0)