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

前端 未结 2 830
囚心锁ツ
囚心锁ツ 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:47

    // 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;
    

提交回复
热议问题