This article mainly introduces PHP's deep-priority and breadth-priority traversal methods for Binary Trees. It involves php's skills related to binary tree traversal and has some reference value. For more information, see
This article mainly introduces PHP's deep-priority and breadth-priority traversal methods for Binary Trees. It involves php's skills related to binary tree traversal and has some reference value. For more information, see
This example describes how PHP implements the depth-first and breadth-first traversal of Binary Trees. Share it with you for your reference. The details are as follows:
# Binary Tree breadth-first traversal # use a queue to implement class Node {public $ data = null; public $ left = null; public $ right = null ;} # @ param $ btree root node function breadth_first_traverse ($ btree) {$ traverse_data = array (); $ queue = array (); array_unshift ($ queue, $ btree ); # root node queuing while (! Empty ($ queue) {# continuous output node until the queue is empty $ cnode = array_pop ($ queue ); # team end element departure $ traverse_data [] = $ cnode-> data; # The left node is first queued, and then the right node is queued if ($ cnode-> left! = Null) array_unshift ($ queue, $ cnode-> left); if ($ cnode-> right! = Null) array_unshift ($ queue, $ cnode-> right);} return $ traverse_data;} # use a stack to implement function depth_first_traverse ($ btree) {$ traverse_data = array (); $ stack = array (); array_push ($ stack, $ btree); while (! Empty ($ stack) {$ cnode = array_pop ($ stack); $ traverse_data [] = $ cnode-> data; if ($ cnode-> right! = Null) array_push ($ stack, $ cnode-> right); if ($ cnode-> left! = Null) array_push ($ stack, $ cnode-> left);} return $ traverse_data;} $ root = new Node (); $ node1 = new Node (); $ node2 = new Node (); $ node3 = new Node (); $ node4 = new Node (); $ node5 = new Node (); $ node6 = new Node (); $ root-> data = 1; $ node1-> data = 2; $ node2-> data = 3; $ node3-> data = 4; $ node4-> data = 5; $ node5-> data = 6; $ node6-> data = 7; $ root-> left = $ node1; $ root-> right = $ node2; $ node1-> left = $ node3; $ node1-> right = $ node4; $ node2-> left = $ node5; $ node2-> right = $ node6; $ traverse = breadth_first_traverse ($ root); print_r ($ traverse); echo ""; $ traverse = depth_first_traverse ($ root); print_r ($ traverse );
I hope this article will help you with php programming.