Skip to content

Instantly share code, notes, and snippets.

@SammyK
Created September 6, 2018 21:54
Show Gist options
  • Save SammyK/4619731949acba9fe23ef9c7f49eb473 to your computer and use it in GitHub Desktop.
Save SammyK/4619731949acba9fe23ef9c7f49eb473 to your computer and use it in GitHub Desktop.
Invert A Binary Tree in PHP (Array Implementation)
<?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