Getting all nodes at a level in full binary tree, array format

坚强是说给别人听的谎言 提交于 2019-12-02 08:25:12

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!