I need to get all the nodes at a certain level in a full binary tree from either the left or right subtree. I currently retrieve the binary tree from the DB as an array, for example:
[1,2,3,4,5,6,7] represents a tree like this:
1
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
So what I need to do is basically grab a level of the tree and return it as an array. Something like level(3,"left") -> [4,5] or level(2, "right") -> [3]. I was thinking about creating a BinaryTree object doing it recursively, but I can't think of a way to keep track of the level within the call without having to tag every node with a level or something like that as I'd like to keep the DB as clean as possible. Any ideas?
Edit: I really need all the nodes at a level for the left or right subtree, not the whole tree. I'm displaying a tournament, so I need to split it half and half. If I didn't have to split it, I could probably do this:
function level($array, $level_num) {
return array_slice($array, pow(2, $level_num)-1, pow(2, $level_num));
}
I don't really know how to extend this for getting only the left or right subtree's level array.
I upvoted BeetleJuice's answer for using the "Shift Left" bitwise operator << -- it is the perfect building block for this task.
This is as clean as I can make my coding attempt:
Code: (Demo)
function getForkinValues($array,$level,$side='left'){ // left side fork is default
if($level==1) return current($array);
$length=$level>2?1<<($level-2):1; // number of elements to return
$index=(1<<$level-1)-1; // first index to return
if($side=='right') $index+=$length; // shift to correct index for 'right'
if(!isset($array[$index+$length-1])) return 'Error: Insufficient Array Length';
return array_slice($array,$index,$length);
}
$array=['A','B','C','D','E','F','G'];
var_export(getForkinValues($array,3,'right'));
// Adjust depth as needed
$depth = 3;
// using bit arithmetic. '<< 3' means multiply by 2 three times.
$start = 1 << $depth-1; // 1 * (2 * 2) because depth is 3
$end = (1 << $depth) -1; // 1 * (2 * 2 * 2) - 1
// if depth=3, this is [4,5,6,7]
$fullLevel = range($start, $end);
print_r($fullLevel);
if($depth > 1):
$leftBranch = array_slice($fullLevel,0,count($fullLevel)/2);
$rightBranch = array_slice($fullLevel,count($fullLevel) / 2);
print_r($leftBranch); // [4,5]
print_r($rightBranch); // [6, 7]
endif;
来源:https://stackoverflow.com/questions/45291652/getting-all-nodes-at-a-level-in-full-binary-tree-array-format