PHP 通過數組判斷數組順序輸出是否是二叉排序樹的後序遍曆結果

來源:互聯網
上載者:User
 1 <?php 2     #通過數組判斷該數組順序輸出是否是二叉樹後序遍曆結果 3      4     #@param a 待判斷數組 5     #@param s 待判斷開始部分 6     #@param e 待判斷結束部分 7     function is_bst_post($a, $s, $e) { 8         if ($s == $e) { 9             return true;10         }11 12         #由於是後序遍曆,所以根節點必然是最後一個元素13         $root = $a[$e];14         #找到第一個大於等於根節點的元素15         #如果符合bst的數組,從s到i-1,都是左子樹元素,i到e-1都是右子樹的元素16         #此處規定二叉樹如果有相同的元素都放在右子樹17         $i = $s;18         while ($i < $e && $a[$i] < $root) $i++;19 20         #分別判斷左右子樹是否是bst21         #如果左子樹存在,判斷左子樹是否是bst22         if ($i > $s) {23             #此處不需要判斷左子樹是否都小於root,因為i左邊的元素都已經是小於root了24             $result_l = is_bst_post($a, $s, $i - 1);25         } else if ($i == $s) { #左子樹不存在26             $result_l = true;27         }28 29         #如果右子樹存在,判斷右子樹是否是bst30         if ($i < $e) {31             #查看右子樹是否所有節點均大於等於root32             for ($j = $i; $j < $e; $j++) {33                 if ($a[$j] < $root) {34                     return false;35                 }36             }37             $result_r = is_bst_post($a, $i, $e - 1);38         } else if ($i == $e) { #右子樹不存在39             $result_r = true;40         }41 42         return ($result_l && $result_r);43     }44 45     $a = array(5, 7, 6, 9, 11, 10, 8);46     $b = array(7, 4, 6, 5);47     $t = is_bst_post($a, 0, count($a) - 1);48     $t2 = is_bst_post($b, 0, count($b) - 1);49     var_dump($t, $t2);50 ?>

bool(true) bool(false)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.