I'm working on my first-ever recursive problem and I'm stuck. First off, I don't believe the function I wrote is actually correct, and I'm sitting in a hospital so there's no access to PHP to actually do some sort of debugging and moving forward with the development of this function. In any case, the purpose of this function is to print a binary tree level by level. My solution is to recurse through the tree, and push the node into a hashmap that has the level as the reference point. Here's my binary tree:
$binary_tree = array(array(1 => array(2 => array(4,5),4=>array(5,6))));
1
|
------------------
| |
2 4
| |
------------- ----------
| | | |
4 5 5 6
And the end result should look like this:
$data[0] = array(1);
$data[1] = array(2,4);
$data[2] = array(4,5,5,6);
As you can see, from this point, I can easily loop through the array and print out the numbers, which are corresponding to the level(the array index).
Here's the function, completely untested and most likely wrong, but my first shot:
function recurse_tree($data,$level=0){
$final = array();
$tmp = array()
// first check if data is array
if(is_array($data)){
// loop through data
foreach($data as $elm){
// push data to the tmp array
$tmp[] = recurse_tree($elm,$level+1);
}
// not an array
} else {
// push data to the final array. can we push to the tmp array.
array_push($final[level],$elm);
}
// merge final and tmp array and return
return ($final + $tmp);
}
I am not too experienced with recursion nor problem solving, so I wrote out the steps below which are occurring. The problem I have here now is that on step 9 I an unsure how to handle the keys 2 and 4, and then finally to handle the root node, key 1. Also, when I get to steps 5-8, im at level 4, which is correct, however according to the tree, its level 2.
$flattened_tree = recurse_tree($data);
// STEPS:
1./ called recurse_tree
data: array(array(1 => array(2 => array(4,5),4=>array(5,6))));
level: 0
final: array();
tmp: array();
2./ called recurse_tree:
data: array(1 => array(2 => array(4,5),4=>array(5,6)));
level: 1
final: array();
tmp: array();
3./ called recurse_tree:
data: array(2 => array(4,5),4=>array(5,6));
level: 2
final: array();
tmp: array();
4./ called recurse_tree:
data: array(4,5)
level: 3
final: array();
tmp: array();
5./ called recurse_tree:
data: 4
level: 4
final: array(4 => 4)
tmp: array()
6./ called recurse_tree:
data: 5
level: 4
final: array(4 => 5)
tmp: array(4 => 4)
7./ called recurse_tree:
data: 5
level: 4
final: array(4=> 5)
tmp: array(4 => array(4,5))
8./ called recurse_tree:
data: 6
level: 4
final: array(4 => 6)
tmp: array(4 => array(4,5,5))
I'm positive that i'm missing several points here, including handling the keys to the arrays. Any help would be greatly appreciated.