This article mainly introduces about PHP based on non-recursive algorithm implementation of the first order/sequence/post-traversal binary tree operation, has a certain reference value, now share to everyone, the need for friends can refer to
/** * PHP Implementation of First Order/middle order/sequential traversal binary tree operation based on non-recursive algorithm * A * B C * D E F G * H * First order traversal: first traverse the root node, then traverse the left node, and finally traverse the right Node: ABDHECFG * Middle sequence traversal: first traversing the left subtree, then traversing the root node, and finally traversing the right subtree: HDBEAFCG * post-order traversal: Walk through the left subtree first, then traverse the right subtree, and finally traverse the root node: HDEBFGCA * *//* First sequence traversal: Using the advanced back-out characteristics of the stack, first access to the root node, and then press the right subtree into the left sub-tree. This is taken out of the left dial hand tree, and finally take out the right subtree */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 into the right subtree} if ($center _node->left! = null) {Array_push ($stack, $center _node->left);//press into left subtree}}}/* Middle sequence traversal: need to traverse from the bottom up, To first press the left subtree into the stack, and then access the root node and the right subtree, */function Inorder ($root) {$stack = array (); $center _node = $root; while (!empty ($stack) | | $cente R_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; }}/* post-Traversal: Save the root node first, then store the Saozi right subtree, then output */function Tailorder ($root) {$stack = array (); $outStack = Array (); Array_push ($ $s Tack, $root); while ($empty ($stack)) {$center _node = Array_pop ($stack); Array_push ($outStack, $center _node); if ($center _node-> Right! = null) {Array_push ($stack, $center _node->left);}} while ($empty ($outStack)) {echo $center _node->value;}}
Related recommendations:
PHP-based Iterator pattern implementation
Php method for generating two-dimensional code based on Phpqrcode class
PHP based on object-oriented implementation of message book function