Home > Backend Development > PHP Tutorial > How to create a binary tree in php (code example)

How to create a binary tree in php (code example)

不言
Release: 2023-04-04 12:40:02
forward
3177 people have browsed it

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
  }
}
Copy after login


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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template