PHP計算二叉樹中某個節點的深度

 

<?php

$arr = [
    [
        "name" => "d",
        "parent" => "b",
    ],
    [
        "name" => "e",
        "parent" => "b",
    ],
    [
        "name" => "f",
        "parent" => "c",
    ],
    [
        "name" => "g",
        "parent" => "c",
    ],

    [
        "name" => "b",
        "parent" => "a",
    ],
    [
        "name" => "c",
        "parent" => "a",
    ],

    [
        "name" => "a",
        "parent" => "",
    ],
];

/**
 * 深度 d
 * 數量 n
 * 複雜度 d*n
 */
$depth = [];
$O = 0;
for($i=0; $i<count($arr); $i++){
    $set = false;
    foreach ($arr as $key => $dArray){
        $name = $dArray["name"];
        $parent = $dArray["parent"];

        if(!isset($depth[$name])){
            if(empty($parent)){
                $depth[$name] = 1;

                unset($arr[$key]);
                $set = true;
            } else {
                if(isset($depth[$parent])){
                    $depth[$name] = $depth[$parent]+1;

                    unset($arr[$key]);
                    $set = true;
                } else {}
            }
        } else {}
        $O++;
    }

    if(!$set){
        break;
    } else {}
}

echo "循環次數={$O}";
var_dump($depth);

輸出:php

循環次數=17
D:\wamp64\www\test.php:73:
array (size=7)
  'a' => int 1
  'b' => int 2
  'c' => int 2
  'd' => int 3
  'e' => int 3
  'f' => int 3
  'g' => int 3
相關文章
相關標籤/搜索