PHP full Binary Tree definition and implementation example, php Binary Tree definition example
This example describes the PHP full Binary Tree definition and implementation method. We will share this with you for your reference. The details are as follows:
If the depth of a binary tree is set to h, in addition to layer h, other layers (1 ~ H-1) are all reached the maximum number of points, the h layer of all nodes are continuously concentrated on the leftmost, This Is The Complete Binary Tree.
PHP code implementation (temporarily add nodes, traverse nodes hierarchically, delete nodes for subsequent updates)
<? Phpclass Node {public $ value; public $ leftNode; public $ rightNode;}/* locate an empty node */function findEmpytNode ($ Node, $ parent = null) {if (empty ($ node-> value) {return $ node;} else {if (empty ($ node-> leftNode-> value )) {return $ node-> leftNode;} else if (empty ($ node-> rightNode-> value) {return $ node-> rightNode ;} else {if (empty ($ parent) | $ node-> value = $ parent-> rightNode-> value) {return findEmpytNode ($ node-> leftNode, $ node);} else {return findEmpytNode ($ parent-> rightNode, $ node) ;}}/ * Add node */function addNode ($ node, $ value) {$ emptyNode = findEmpytNode ($ node); setNode ($ emptyNode, $ value);}/* Set node */function setNode ($ node, $ value) {$ node-> value = $ value; $ node-> leftNode = new Node (); $ node-> rightNode = new Node ();} /* print */function printTree ($ node, $ parent = null) {if (empty ($ node-> value) return; echo $ node-> leftNode-> value; echo $ node-> rightNode-> value; if (empty ($ parent) | $ node-> value = $ parent-> rightNode-> value) {printTree ($ node-> leftNode, $ node);} else {printTree ($ parent-> rightNode, $ node) ;}}$ head = new Node (); setNode ($ head, 1); addNode ($ head, 2); addNode ($ head, 3); addNode ($ head, 4); addNode ($ head, 5 ); addNode ($ head, 6); printTree ($ head );