首頁  >  文章  >  後端開發  >  php如何實現二元樹的深度計算(附程式碼)

php如何實現二元樹的深度計算(附程式碼)

不言
不言轉載
2018-10-09 14:41:073191瀏覽

這篇文章帶給大家的內容是關於php如何實現二元樹的深度計算(附程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

二元樹的深度:
輸入一棵二元樹,求該樹的深度。從根結點到葉結點依序經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。

想法:

1.非遞歸層序遍歷
2.使用輔助佇列,根結點先入佇列
3. 循環判斷佇列是否為空,如果不為空就繼續循環隊列裡面的每個結點
4. 循環隊列時,當前當前結點出隊列,把該結點的左右孩子入隊列

TreeDepth(tree)
    if !tree return 0
    array_push(queue,tree);
    depth=0
    while(!empty(queue)){
        ++depth
        for i=0;i<queue.size;i++
            node=array_pop(queue)
            array_push(queue,node->left);
            array_push(queue,node->right);
    return depth
<?php
class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }   
}
function TreeDepth($tree)
{
        if(!$tree) return 0;
        $queue=array();
        array_push($queue,$tree);//在数组最后添加元素
        $depth=0;
        while(!empty($queue)){
                $depth++;
                $size=count($queue);
    
                for($i=0;$i<$size;$i++){
                        $node=array_shift($queue);//非常重要 删除第一个元素
                        if($node->left){
                                array_push($queue,$node->left);
                        }   
                        if($node->right){
                                array_push($queue,$node->right);
                        }   
                }   
        }    
        return $depth;
}
$node1=new TreeNode(1);
$node2=new TreeNode(2);
$node3=new TreeNode(3);
$node4=new TreeNode(4);
$node5=new TreeNode(5);
$node6=new TreeNode(6);
$node7=new TreeNode(7);
$tree=$node1;
$node1->left=$node2;
$node1->right=$node3;
$node2->left=$node4;
$node2->right=$node5;
$node4->right=$node6;
$node3->left=$node7;
var_dump($tree);
$dep=TreeDepth($tree);
var_dump($dep);

以上是php如何實現二元樹的深度計算(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除