• 二叉搜索树实现


    class Node {
    		public $data;
    		public $left;
    		public $right;
    
    		public function __construct($data){
    			$this->data=$data;
    		}
    	}
    	class CreateTree{
    		public $tree;
    		//二叉树进行插入
    		public function insert($data){
    			if(!$this->tree){
    				$this->tree = new Node($data);
    				return ;
    			}
    			$p = $this->tree;
    			while($p){
    				if($data < $p->data ){
    					if(!$p->left){
    						$p->left = new Node($data);
    						return ;
    					}
    					$p= $p->left;
    				}elseif($data > $p->data){
    					if(!$p->right){
    						$p->right = new Node($data);
    						return;
    					}
    					$p=$p->right;
    				}
    			}
    		}
    
    		//对二叉树进行遍历
    		public function midOrder($node){
    			if($node->data == null){
    				return ;
    			}
    			echo $node->data;	
    			echo "\r\n";
    			if($node->left != null){
    				$this->midOrder($node->left);
    			}
    
    			if($node->right != null){
    				$this->midOrder($node->right);
    			}
    
    		}
    
    		public function searchData($data){
    			$p = $this->tree;
    			while($p){
    				if($data < $p->data){
    					$p = $p->left;
    				}elseif($data > $p->data){
    					$p=$p->right;
    				}else{
    					return $p;
    				}
    			}
    			return null;
    		}
    		//删除某个数字
    		public function remoteData($data){
    			if($this->tree== null){
    				return "";
    			}			
    			$p = $this->tree;
    			while($p && $p->data != $data){
    				$pp = $p;
    				if($data < $p->data){
    					$p = $p->left;
    				}
    				if($data > $p->data){
    					$p=$p->right;
    				}
    			}
    			if($p == null){
    				return ;
    			}
    
    			if($p->left && $p->right){
    				$minP =$p->right;
    				while($minP->left){
    					$minPP = $minP;
    					$minP = $minP->left;
    				}
    				$p->data = $minP->data;//赋值
    				$p=$minP;
    				$pp = $minPP;
    			}
    			$child=null;
    			if($p->left){
    				$child = $p->left;
    			}
    			if($p->right){
    				$child = $p->right;
    			}
    
    			if($pp->left == $p){
    				$pp->left = $child;
    			}else{
    				$pp->right = $child;
    			}
    
    		}
    	}
    
    	$objcreate  = new CreateTree();
    
    	$arr = array(33,16,50,13,18,34,58,15,17,25,51,66,19,27,55);
    	foreach ($arr as $key => $value) {
    		$objcreate->insert($value);
    	}
    	$tree = $objcreate->tree;
    	$data=13;
    	$objcreate->remoteData($data);
    	$objcreate->midOrder($tree);
    

      

  • 相关阅读:
    配置IIS Express 7.5以允许外部访问
    免费CDN /初体验 访问量激升19%
    微软发布IIS Express:Visual Studio全新内置的Web服务器
    Visual Studio智能提示突然消失的解决办法 (vs2008 vs2010 vs2012 智能提示)
    深入理解HTTP协议
    TSO、UFO、GSO、LRO、GRO和RSS介绍
    MERGE表的问题
    使用zypper安装软件
    Mysql遇到Too many connections的解决办法
    处理SecureCRT中使用vim出现中文乱码问题
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12089152.html
Copyright © 2020-2023  润新知