• 二叉搜索树实现


    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);
    

      

  • 相关阅读:
    500. 键盘行
    657. 判断路线成圈
    771. 宝石与石头
    461. 汉明距离
    Java 基本数据类型
    Windows下的DOM操作
    jQuery学习笔记
    Java(16-19)
    Java(1-15)
    总结
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12089152.html
Copyright © 2020-2023  润新知