So there is this problem essentially, What we are doing to invert the Tree is
- Create a new TreeNode
- Assign root->left to ->right
- Assign root->right to ->left
The solution is
function invertTree(root) {
const queue = [root];
while (queue.length) {
const n = queue.pop();
if (n != null) {
[n.left, n.right] = [n.right, n.left];
queue.push(n.left, n.right);
}
}
return root;
};
However, the part I am confused about is the change was made to queue not to root. why are we returning root at the end? It seems like we have direct access to the reference of the initial root. I thought the root inside the queue is a copy of the root. that's the part I am confused about. why is it a reference and not a copy? is it because we have not used new Array()?