Created
September 6, 2018 21:54
-
-
Save SammyK/4619731949acba9fe23ef9c7f49eb473 to your computer and use it in GitHub Desktop.
Invert A Binary Tree in PHP (Array Implementation)
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
<?php | |
// Similar, but not quite the same as LeetCode problem #226 | |
// @see https://leetcode.com/problems/invert-binary-tree/description/ | |
function invertTree(array $nodes): array | |
{ | |
$height = (int) floor(log(count($nodes), 2)); | |
$level = 1; | |
while ($level <= $height) { | |
$start = 2 ** $level - 1; | |
$end = 2 * $start; | |
while ($end > $start) { | |
$temp = $nodes[$start]; | |
$nodes[$start] = $nodes[$end]; | |
$nodes[$end] = $temp; | |
$end--; | |
$start++; | |
} | |
$level++; | |
} | |
return $nodes; | |
} | |
var_export(invertTree([4,2,7,1,3,6,9])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment