猿问

请看这份深度优先搜索代码,为何用引用就找不到?

function search(&$node, &$forest, $id)
{
    $node = null;
    $len = count($forest);
    for ($i=0; $i<$len; ++$i)
    {
        if ($forest[$i]['id'] == $id)
        {
            $node = &$forest[$i]; //【去掉“&”就能找到,加上就找不到】
            return;
        }

        search($node, $forest[$i]['children'], $id);
        if ($node) { return; }
    }
}

$forest = array(
    array(
        'id' => 1,
        'pid' => 0,
        'children' => array(
            array(
                'id' => 11,
                'pid' => 1,
                'children' => array(),
            ),
        ),
    ),
    array(
        'id' => 2,
        'pid' => 0,
        'children' => array(),
    ),
);

search($node, $forest, 11);
echo json_encode($node);
慕仙森
浏览 411回答 1
1回答
随时随地看视频慕课网APP
我要回答