Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created August 14, 2024 06:45
Show Gist options
  • Save kshirish/4c188291404e589d7d2f17ff5ff1a98d to your computer and use it in GitHub Desktop.
Save kshirish/4c188291404e589d7d2f17ff5ff1a98d to your computer and use it in GitHub Desktop.
Binary Tree - inverse (mirror)
// Example 1:
// Input: root = [4,2,7,1,3,6,9]
// Output: [4,7,2,9,6,3,1]
// Example 2:
// Input: root = [4,2,7,1,3,6]
// Output: [4,7,2,6,3,1]
// Example 3:
// Input: root = [2,1,3]
// Output: [2,3,1]
function reverse(arr, startIndex, endIndex) {
for (let i = startIndex; i <= Math.floor((startIndex + endIndex) / 2); i++) {
let temp = arr[i];
arr[i] = arr[endIndex - i + startIndex];
arr[endIndex - i + startIndex] = temp;
}
}
function inverseBinaryTree(arr) {
let i = 0;
let toThePower = 0;
while (i < arr.length) {
const jump = Math.pow(2, toThePower);
reverse(arr, i, Math.min(i + jump - 1, arr.length - 1));
i = i + jump;
toThePower += 1;
}
return arr;
}
inverseBinaryTree([4, 2, 7, 1, 3, 6, 9]);
inverseBinaryTree([4, 2, 7, 1, 3, 6]);
inverseBinaryTree([4, 2, 7, 1, 3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment