PHP uses non-recursive algorithms to implement first-order, middle-order, and post-order traversal of Binary Tree operation examples. Recursive Binary Tree
This example describes how PHP uses non-recursive algorithms to traverse Binary Trees in ascending, central, and descending order. We will share this with you for your reference. The details are as follows:
Overview:
The principle of binary tree traversal is as follows:
For binary tree traversal:
1. Forward traversal: First traverse the root node, then traverse the left subtree, and finally traverse the right subtree.
ABDHECFG
2. Middle-order traversal: First traverse the left subtree, then traverse the root node, and finally traverse the right subtree.
HDBEAFCG
3. Post-order traversal: First traverse the left subtree, then traverse the right subtree, and finally traverse the root node.
HDEBFGCA
Implementation Method:
Sequential traversal:With the advanced and later features of the stack, access the root node first, then press the right subtree into the left subtree. In this way, the left subtree is extracted first, and then the right subtree is extracted.
Function preorder ($ root) {$ stack = array (); array_push ($ stack, $ root); while (! Empty ($ stack) {$ center_node = array_pop ($ stack); echo $ center_node-> value; // root node if ($ center_node-> right! = Null) array_push ($ stack, $ center_node-> right); // press the right subtree if ($ center_node-> left! = Null) array_push ($ stack, $ center_node-> left); // press the left subtree }}
Central order:We need to traverse from the bottom up, so we first press the left subtree into the stack, and then access the root node and the right subtree one by one.
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; }}
Descending order:First, store the root node, and then store the left and right subtree in sequence. Then output.
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; }}