Last active
December 8, 2021 02:42
-
-
Save Braunson/dad8c44ce1d58b507a60e6031eaae4d6 to your computer and use it in GitHub Desktop.
Dealing with binary trees represented as arrays and determining weather the left or right branch of the tree is larger. The size of each branch is the sum of the node values. (`-1` is considered a non-existent node)
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 | |
function solution($arr) | |
{ | |
// If the array is empty or there is only 1 value | |
if (count($arr) <= 1) { | |
return ''; | |
} | |
// A quick check as to not redefine the function | |
if (!function_exists('innerSolution')) { | |
function innerSolution($arr, $index) | |
{ | |
if ($index - 1 < count($arr)) { | |
if ($arr[$index - 1] === -1) { | |
return 0; | |
} | |
return $arr[$index - 1] + | |
innerSolution($arr, $index * 2) + | |
innerSolution($arr, $index * 2 + 1); | |
} | |
return 0; | |
} | |
} | |
$left = innerSolution($arr, 2); | |
$right = innerSolution($arr, 3); | |
return ($left == $right) ? '' : ($left < $right ? 'Right' : 'Left'); | |
} | |
// The test array and expected solutions | |
$testArray = [ | |
// Array contains test array as well as expected solution | |
[[3, 6, 9, -1, 10], 'Left'], | |
[[1, 4, 100, 5], 'Right'], | |
[[1, 10, 5, 1, 0, 6], ''], | |
[[1], ''], | |
[[], ''], | |
]; | |
// Loop through the test array | |
$i = 0; | |
foreach ($testArray as $test) { | |
$i++; | |
// Determine our variables to use the array and the expected solution | |
$arr = $test[0]; | |
$solution = $test[1]; | |
// Run the test | |
$result = solution($arr); | |
// Did the solution pass or fail | |
$status = $result == $solution ? '✔️ PASS' : '❌ FAIL'; | |
// Some checking for purely test result purposes | |
if (empty($solution)) $solution = "''"; | |
if (empty($result)) $result = "''"; | |
// Dump out some visual info on the tests | |
print("Test Case {$i}: {$status}\r\n"); | |
print(" Expected: {$solution}\r\n"); | |
print(" Result: {$result}\r\n\r\n"); | |
} |
Thanks for sharing this @Braunson , much appreciated! Excellent use of recursion for forming the binary tree from one-dimensional array! I tried the same solution with JavaScript and it worked fine, sharing it here if its useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected output would look like this..