二叉搜索树(递归和非递归分别实现)

来源:互联网 发布:武林外传 知乎精华 编辑:程序博客网 时间:2024/05/18 00:29

这是在上一篇博客的基础上进行完善。

1.插入的递归

bool InsertR(const T& key){return _InsertR(_root,key);}

bool _InsertR(Node*& root,const T& key){if(root==NULL){root=new Node(key);return true;}if(root->_key>key){return _InsertR(root->_left ,key);}else if(root->_key <key){return _InsertR(root->_right ,key);}else  //这个数存在root->_key==key{return false;}}

2.插入的非递归

bool Insert(const T& key){//1.空树//2.不存在//3.存在//空树if(_root==NULL){_root=new Node(key);return true;}Node* cur=_root;Node* prev=cur;while(cur){if(cur->_key >key){prev=cur;cur=cur->_left ;}    else if(cur->_key <key){prev=cur;cur=cur->_right ;}else //if(cur->_key ==key)return false;  //存在}//不存在if(prev->_key >key){cur=new Node(key);    prev->_left =cur;}else{cur=new Node(key);    prev->_right =cur;}return true;}

3.删除的非递归

bool Remove(const T& key){if(_root==NULL)return false;Node* cur=_root;Node* parent=NULL;while(cur){if(cur->_key <key){parent=cur;cur=cur->_right ;}else if(cur->_key >key){parent=cur;cur=cur->_left ;}else    //找到key,再删除{if(cur->_left==NULL )   //左为空{if(_root==cur){_root=cur->_right ;}else if(parent->_left ==cur){parent->_left =cur->_right ;}else{parent->_right =cur->_right ;}delete cur;}else if(cur->_right ==NULL)  //右为空{if(_root==cur){_root=cur->_left ;}else if(parent->_left ==cur){parent->_left =cur->_left ;    }else{parent->_right =cur->_left ;}delete cur;}else    //删除的节点左右都不为空{//找右子树的最左节点Node* righttree=cur->_right ;parent=cur;while(righttree->_left ){parent=righttree;righttree=righttree->_left ;}if(parent->_left ==righttree){parent->_left =righttree->_right ;}else{parent->_right =righttree->_right ;}}return true;}}return false;}


4.删除的递归

bool RemoveR(const T& key){    return _RemoveR(_root,key);}
bool _RemoveR(Node*& root,const T& key)//&这个是重点{if(root==NULL)return false;if(root->_key <key)return _RemoveR(root->_right ,key);else if(root->_key >key)    return _RemoveR(root->_left ,key);else    //找到,再删除{Node* del=root;if(root->_left ==NULL){root=root->_right ;}else{root=root->_left ;}delete del;}}
5.查找的非递归

bool Find(const T& key){Node* cur=_root;while(cur){if(cur->_key <key){cur=cur->_right ;}else if(cur->_key >key){cur=cur->_left ;}else if(cur->_key ==key)return true;}return false;}

6.查找的递归

bool FindR(const T& key){_FindR(_root,key);}

bool _FindR(Node* root,const T& key){if(root==NULL)return false;if(root->_key >key)    return _FindR(root->_left ,key);else if(root->_key <key)return _FindR(root->_right ,key);elsereturn true;}

7.中序遍历

void InOrderR(){_InOrderR(_root);cout<<endl;}

void _InOrderR(Node* root){if(root==NULL)return;   _InOrderR(root->_left );   cout<<root->_key<<" " ;   _InOrderR(root->_right );}





0 0
原创粉丝点击