数据结构之树结构

数据结构中的树是一种非常重要的数据结构,其包括二叉树、平衡树、红黑树等多种类型。在PHP语言中,我们可以用类或面向对象的方法实现树,以下是几种常见树的原理和PHP代码实现。

1. 二叉树(Binary Tree)

二叉树是树的一种特殊形式,每个节点最多有两个子节点,左子节点小于父节点,右子节点大于父节点。如果左右子树都为空,则该节点是叶子节点。

以下是PHP代码实现二叉树:

class Node {
    public $data; // 节点值
    public $leftChild; // 左子节点
    public $rightChild; // 右子节点

    public function __construct($data) {
        $this->data = $data;
        $this->leftChild = null;
        $this->rightChild = null;
    }
}

class BinaryTree {
    private $root; // 根节点

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

    public function insert($data) {
        $newNode = new Node($data);
        if ($this->root == null) {
            $this->root = $newNode;
        } else {
            $current = $this->root;
            while (true) {
                if ($data < $current->data) {
                    if ($current->leftChild == null) {
                        $current->leftChild = $newNode;
                        break;
                    } else {
                        $current = $current->leftChild;
                    }
                } else {
                    if ($current->rightChild == null) {
                        $current->rightChild = $newNode;
                        break;
                    } else {
                        $current = $current->rightChild;
                    }
                }
            }
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值