搜索二叉樹代碼解析(增、刪、改、查)

/*二叉搜索樹的查找操作*/ 
//查找效率決定於樹的高度 
 position find(elementtype x,bintree bst)//尾遞歸 
 {
 	if(!bst) return NULL;//查找失敗
	if(x>bst->data)
	{
		return find(x,bst->right);//在右子樹中繼續查找 
	 } 
	 else if(x<bst->data)
	 {
	 	return find(x,bst->left);//在左子樹裏面繼續查找 
	  } 
	else return bst;//查找成功,返回節點的找到節點的地址 
 }
 /*用循環實現*/ 
  position iterfind(elementtype x,bintree bst)
  {
  	while(bst)
  	{
  		if(x>bst->data) 
  		{
  			bst=bst->right; //向右子樹中移動,繼續查找 
		}
		else if(x<bst->data)
		{
		    bst=bst->left;	//向左子樹中移動,繼續查找 
		}
		else  return bst; //查找成功,返回節點的找到節點的地址 
	}
	return NULL;  //查找失敗 
  }
 /*最小值和最大值的查找*/ 
 //左小右大 
 position findmin(bintree bst) //找最小值 遞歸實現 
 {
 	if(!bst)  return NULL;//空的二叉搜索樹,返回NULL 
	else if(!bst->left)
	{
		return bst; //找到最左葉節點並返回 
	 } 
	else
	{
		return findmin(bst->left); //沿左分支繼續查找 
	}
  } 
  position findmax(bintree bst) // 找最大值 循環實現, 
  {
  	if(bst)
  	{
  		while(bst->right)
  		{
  			bst=bst->right;
		}
	}
	return bst;
   } 
 /*二叉搜索樹的插入*/
 position insert(elementtype x,bintree bst)
 {
 	if(!bst) //若原樹爲空,生成並返回一個節點的二叉搜索樹 
 	{
 		bst=malloc(sizeof(struct treenode));
 		bst->data=x;
 		bst->left=bst->right=NULL;
	}
	else //遞歸插入 
	{
		if(x<bst->data)
		{
			bst->left=insert(x,bst->left);
		}
		else if(x>bst->right)
		{
			bst->right=insert(x,bst->right);
		}
	 }
	 return bst; 
 }
 /*二叉搜索樹的刪除*/
bintree delete(elementtype x,bintree bst)
{
	position tmp;
	if(!bst) printf("要刪除的元素未找到");
	else if(x<bst->data)
	{
		bst->left=delete(x,bst->left);//左子樹遞歸刪除 
	 } 
	else if(x>bst->right)
	{
		bst->right=delete(x,bst->right);//右子樹遞歸刪除 
	 } 
	 else 
	    if(bst->left&&bst->right) //被刪除的節點有左右兩個子節點
	    {
	    	tmp=findmin(bst->right)//在右子樹中找做小的元素填充刪除節點
			bst->data=tmp->data;
			bst->right=delete(bst->data,bst->right);//在右子樹中找最小的元素填充刪除節點 
		} 
		else //被刪除節點有一個或者這無子節點 
		{
			tmp=bst;
			if(!bst->left)//有右孩子或無子節點 
			{
				bst=bst->right;
			}
			else if(!bst->right)//有左孩子或無子節點 
			{
				bst=bst->left;
			}
			free(tmp);
		}
	return bst;
}

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章