Learner Level
Implement the invertBinaryTreeValues method that returns binary tree values after inverting left and right children.
The input contains a binary tree represented as an integer array tree in level-order format.
Your task is to invert the binary tree and return the inverted tree values in level-order format. Inverting a tree means every left child and right child are swapped.
For example, [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1].
Invert the tree by swapping the left and right child of every node.
Start from the root. Swap its left and right children, then repeat the same process for the left subtree and the right subtree. This mirrors the complete tree.
Because the tree is stored as an array, the left child index is 2 * index + 1 and the right child index is 2 * index + 2.
Pseudocode:
function invertBinaryTreeValues(tree, size):
result = copy of tree
invert(0)
return result
function invert(index):
if index >= size or result[index] is missing:
return
left = 2 * index + 1
right = 2 * index + 2
if left < size and right < size:
swap result[left] and result[right]
invert(left)
invert(right)