Home >Backend Development >PHP Tutorial >How to create a binary tree in php (code example)
The content of this article is about how to create a binary tree in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Use the principle of recursion, except that where the node was originally printed, it is changed to the operation of generating the node and assigning a value to the node
if(ch=='#' ){*T=NULL;}else{malloc();(*T)->data=ch;createFunc((*T)->lchild);createFunc((*T)->rchild);}
2. Preorder traversal: visit the root node first, traverse the left subtree in preorder, traverse the right subtree in preorder; left and right in the middle
3. Put the values of each node in the binary tree The null pointer leads to a virtual node whose value is a specific value#. The binary tree processed is an extended binary tree of the original binary tree. The extended binary tree achieves a traversal sequence to determine a binary tree
<?php class BinTree{ public $data; public $left; public $right; } //前序遍历生成二叉树 function createBinTree(){ $handle=fopen("php://stdin","r"); $e=trim(fgets($handle)); if($e=="#"){ $binTree=null; }else{ $binTree=new BinTree(); $binTree->data=$e; $binTree->left=createBinTree(); $binTree->right=createBinTree(); } return $binTree; } $tree=createBinTree(); var_dump($tree); # object(BinTree)#1 (3) { ["data"]=> string(1) "A" ["left"]=> object(BinTree)#2 (3) { ["data"]=> string(1) "B" ["left"]=> NULL ["right"]=> object(BinTree)#3 (3) { ["data"]=> string(1) "D" ["left"]=> NULL ["right"]=> NULL } } ["right"]=> object(BinTree)#4 (3) { ["data"]=> string(1) "C" ["left"]=> NULL ["right"]=> NULL } }
The above is the detailed content of How to create a binary tree in php (code example). For more information, please follow other related articles on the PHP Chinese website!