Created
August 14, 2024 06:45
-
-
Save kshirish/4c188291404e589d7d2f17ff5ff1a98d to your computer and use it in GitHub Desktop.
Binary Tree - inverse (mirror)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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