1. 程式人生 > >二叉排序樹插入演算法之php實現

二叉排序樹插入演算法之php實現

        插入是基於查詢的過程,如果找不到,通過最後一個被查詢的節點判斷,如果查詢值小於該節點,將查詢值賦予

該節點的左孩子,否則賦予該節點的右孩子。

        程式碼如下:

<?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";