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

输出:

循环次数=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

 

转载于:https://my.oschina.net/u/4054486/blog/3081534

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值