PHP full Binary Tree definition and implementation example, php Binary Tree definition example

Source: Internet
Author: User

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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.