Skip to content

Instantly share code, notes, and snippets.

@Braunson
Last active December 8, 2021 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Braunson/dad8c44ce1d58b507a60e6031eaae4d6 to your computer and use it in GitHub Desktop.
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)
<?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");
}
@Braunson
Copy link
Author

Expected output would look like this..

Test Case 1: ✔️ PASS
   Expected: Left
   Result:   Left

Test Case 2: ✔️ PASS
   Expected: Right
   Result:   Right

Test Case 3: ✔️ PASS
   Expected: ''
   Result:   ''

Test Case 4: ✔️ PASS
   Expected: ''
   Result:   ''

Test Case 5: ✔️ PASS
   Expected: ''
   Result:   ''

@razniceguy
Copy link

razniceguy commented Dec 8, 2021

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