本文主要介紹了PHP基於非遞歸演算法實現先序、中序及後序遍歷二元樹操作,結合實例形式分析了php採用非遞歸演算法對二元樹進行先序、中序及後序遍歷操作的原理與具體實現技巧,需要的朋友可以參考下,希望能幫助大家。
概述:
二元樹遍歷原理如下:
#針對上圖所示二元樹遍歷:
##1.前序遍歷:先遍歷根結點,然後遍歷左子樹,最後遍歷右子樹。 ABDHECFG2.中序遍歷:先遍歷左子樹,再遍歷根結點,最後遍歷右子樹。 HDBEAFCG3.後序遍歷:先遍歷左子樹,然後遍歷右子樹,最後遍歷根節點。 HDEBFGCA實作方法:先序遍歷:利用堆疊先進後出的特性,先訪問根節點,再把右子樹壓入,再壓入左子樹。這樣取出的時候是先取出左子樹,最後再取出右子樹。function preorder($root){ $stack = array(); array_push($stack, $root); while(!empty($stack)){ $center_node = array_pop($stack); echo $center_node->value; // 根节点 if($center_node->right != null) array_push($stack, $center_node->right); // 压入右子树 if($center_node->left != null) array_push($stack, $center_node->left); // 压入左子树 } }
function inorder($root){ $stack = array(); $center_node = $root; while(!empty($stack) || $center_node != null){ while($center_node != null){ array_push($stack, $center_node); $center_node = $center_node->left; } $center_node = array_pop($stack); echo $center_node->value; $center_node = $center_node->right; } }
function tailorder($root){ $stack = array(); $outstack = array(); array_push($$stack, $root); while($empty($stack)){ $center_node = array_pop($stack); array_push($outstack, $center_node); if($center_node->right != null) array_push($stack, $center_node->right); if($center_node->left != null) array_push($stack, $center_node->left); } while($empty($outstack)){ $center_node = array_pop($outstack); echo $center_node->value; } }相關推薦:
以上是PHP實作先序、中序及後序遍歷二元樹操作實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!