Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

二叉树 php

作者:妳會吥會在吥經意間想起莪?   发布日期:2026-01-26   浏览:103

在PHP中,可以使用类来实现二叉树的数据结构。下面是一个简单的二叉树类的示例:

class TreeNode {
    public $data;
    public $left;
    public $right;

    public function __construct($data) {
        $this->data = $data;
        $this->left = null;
        $this->right = null;
    }
}

class BinaryTree {
    public $root;

    public function __construct() {
        $this->root = null;
    }

    public function insert($data) {
        $newNode = new TreeNode($data);

        if ($this->root === null) {
            $this->root = $newNode;
        } else {
            $current = $this->root;
            while (true) {
                if ($data < $current->data) {
                    if ($current->left === null) {
                        $current->left = $newNode;
                        break;
                    }
                    $current = $current->left;
                } else {
                    if ($current->right === null) {
                        $current->right = $newNode;
                        break;
                    }
                    $current = $current->right;
                }
            }
        }
    }

    public function search($data) {
        $current = $this->root;
        while ($current !== null) {
            if ($data == $current->data) {
                return true;
            } elseif ($data < $current->data) {
                $current = $current->left;
            } else {
                $current = $current->right;
            }
        }
        return false;
    }
}

使用示例:

$tree = new BinaryTree();
$tree->insert(5);
$tree->insert(3);
$tree->insert(7);
$tree->insert(2);
$tree->insert(4);

echo $tree->search(4); // 输出: 1 (存在)
echo $tree->search(6); // 输出: 0 (不存在)

这只是一个简单的二叉树实现,还可以根据需要扩展其他功能,如删除节点、遍历等。

上一篇:php把数字转为数组

下一篇:php从大到小输出

大家都在看

php session用法

php 定义常量

php soapclient

phpisset函数

php html转图片

php后端

php爬虫框架

php多线程与并发

php读取csv文件

php+mysql动态网站开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站