二叉排序树插入算法之php实现

8 篇文章 0 订阅

        插入是基于查找的过程,如果找不到,通过最后一个被查找的节点判断,如果查找值小于该节点,将查找值赋予

该节点的左孩子,否则赋予该节点的右孩子。

        代码如下:

<?php
	class BinaryTree
	{
		public $data;
		public $lChild;
		public $rChild;

		public function __construct($data, $lChild = null, $rChild = null)
		{
			$this->data   = $data;
			$this->lChild = $lChild;
			$this->rChild = $rChild;
		}
	}

	$b37 = new BinaryTree(37);
	$b35 = new BinaryTree(35, null, $b37);
	$b51 = new BinaryTree(51);
	$b47 = new BinaryTree(47, $b35, $b51);
	$b58 = new BinaryTree(58, $b47);

	$b93 = new BinaryTree(93);
	$b99 = new BinaryTree(99, $b93);
	$b73 = new BinaryTree(73);
	$b88 = new BinaryTree(88, $b73, $b99);

	$binaryTree = new BinaryTree(62, $b58, $b88);

	$tmp = null;
	function searchBst($binaryTree, $key)
	{
		if (is_null($binaryTree)) {
			return false;
		} else {
			global $tmp;
			$tmp = $binaryTree;
		}
		if ($binaryTree->data == $key) {
			return true;
		} else if ($key < $binaryTree->data) {
			return searchBst($binaryTree->lChild, $key);
		} else {
			return searchBst($binaryTree->rChild, $key);
		}
	}

	// $res = searchBst($binaryTree, 99);
	// print_r($res);echo "\n";
	// print_r($tmp);echo "\n";

	//二叉排序树插入操作
	function InsertBst(&$binaryTree, $key)
	{
		global $tmp;
		if (!searchBst($binaryTree, $key)) {
			$data = new BinaryTree($key);
			$data->lChild = $data->rChild = null;

			if (!$tmp) {
				$binaryTree = $data;
			} else if ($key < $tmp->data) {
				$tmp->lChild = $data;
			} else {
				$tmp->rChild = $data;
			}

			return true;
		}

		return false;
	}

	// $res = InsertBst($binaryTree, 93);
	// print_r($res);echo "\n";
	// print_r($tmp);echo "\n";
	// print_r($binaryTree);echo "\n";

	$binaryTree = null;
	$tree = array(62,88,58,47,35,73,51,99,37,93);
	foreach ($tree as $key => $value) {
		# code...
		InsertBst($binaryTree, $value);
	}
	print_r($binaryTree);echo "\n";

            

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从心所愿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值