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 about how to implement binary tree depth-first and breadth-first traversal in PHP, see the example in this article. 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); # the team end element leaves the queue $ traverse_data [] = $ cnode-> data; # the left node enters the queue first, and the right node enters the queue 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.