PHP 計算二叉樹距離最長的兩個節點間的距離

來源:互聯網
上載者:User
 1 <?php 2     #尋找二叉樹距離最長的兩個節點的距離,即相距邊數最多的兩個節點的邊數 3     #解題思路:距離最長的兩個節點有以下3中情況 4     #1.兩個節點一個位於左子樹,一個位於右子樹,則最長距離是左右子樹的深度相加 5     #2.兩個節點都位於左子樹,則最長距離是以左子樹為根節點的左子樹的兩個左右子樹的深度相加 6     #3.兩個節點都位於右子樹,則最長距離是以右子樹為根節點的右子樹的兩個左右子樹的深度相加 7  8     class Node { 9         public $data = null;10         public $left = null;11         public $right = null;12         public $parent = null;13     }14 15     function get_max_long($root, &$depth) {16         #此處結合二叉樹的深度計算17         if ($root == null) {18             $depth = 0;19             return 0;20         }21         #計算左右子樹的最長距離,同時計算左右子樹深度22         $left_max = get_max_long($root->left, $ld);23         $right_max = get_max_long($root->right, $rd);24         $depth = max($ld, $rd) + 1;25 26         // echo "{$ld}|{$rd}|{$left_max}|{$right_max}<br>";27         return max($ld + $rd, max($left_max, $right_max));28     }29 30     #二叉樹深度演算法31     #此處不用32     function get_depth($root) {33         if (!$root) {34             return 0;35         }36 37         $ld = get_depth($root->left) + 1;38         $rd = get_depth($root->right) + 1;39 40         return max($ld, $rd);41     }42 43     $root = new Node();44     $n1 = new Node();45     $n2 = new Node();46     $n11 = new Node();47     $n12 = new Node();48     $n13 = new Node();49     $n14 = new Node();50     $n15 = new Node();51     $n21 = new Node();52 53     $root->left = $n1;54     $root->right = $n2;55     $n1->left = $n11;56     $n1->right = $n12;57     $n11->left = $n13;58     $n12->right = $n14;59     $n13->left = $n15;60     $n2->right = $n21;61 62     $max = get_max_long($root, $depth);63     echo $max;64 ?>

4 10 3 1 7 11 8 2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.