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)