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

前端 未结 2 834
囚心锁ツ
囚心锁ツ 2021-01-28 04:52

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 exa

2条回答
  •  爱一瞬间的悲伤
    2021-01-28 05:45

    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'));
    

提交回复
热议问题