第十二章:二叉查找树(2)

二叉查找树的插入和删除操作

//非递归插入
void Tree_Insert(TreeNode *root,TreeNode *t){
	TreeNode *parent=NULL;
	while (root){
		parent=root;
		if (t->data>root->data){
			root=root->right;
		}else{
			root=root->left;
		}
	}
	if (!parent){		//如果是空树
		root=t;
	}else{
		if (t->data>parent->data){
			parent->right=t;
			t->parent=parent;
		}else{
			parent->left=t;
			t->parent=parent;
		}
	}
}

//非递归删除
TreeNode *Tree_Delete(TreeNode *root,TreeNode *del){
	TreeNode *t=NULL,*p=NULL;
	if (root&&del){
		if (!del->left||!del->right){
			t=del;
		}else{
			t=Tree_Successor(del);
		}
		if (t->left){
			p=t->left;
		}else{
			p=t->left;
		}
		if (p){
			p->parent=t->parent;
		}
		if(!t->parent){
			root=p;
		}else if (t==t->parent->left){
			t->parent->left=p;
		}else{
			t->parent->right=p;
		}
		if (t!=del){
			del->data=t->data;
		}
	}
	return t;
}

  

posted @ 2013-06-21 15:39  雨夜听声  阅读(159)  评论(0编辑  收藏  举报