树形搜索主要有: 1 二叉搜索树 2 AVL树 3 红黑树 4 Trie树 二叉搜索树: #include<iostream> using namespace std; class BinarySearchTree; class BinaryNode { public: int element; BinaryNode*leftChild,*rightChild; BinaryNode(int m_element,BinaryNode*lt,BinaryNode*rt):element(m_element),leftChild(lt),rightChild(rt){} friend class BinarySerchTree; }; class BinarySearchTree { public: BinaryNode*root; BinarySearchTree(BinaryNode* m_root){root=m_root;} // void insert(BinaryNode* &pNode,int value); BinaryNode* findMax(BinaryNode* t) const; //查找最大值 BinaryNode* findMin(BinaryNode* t) const; //查找最小值 BinaryNode*find(int x,BinaryNode*t) const; //查找函数 void insert(int x,BinaryNode*&t); //插入函数 void remove(int x,BinaryNode*&t); //删除节点函数 void removeMin(BinaryNode*&t); //删除最小值节点函数 }; /*void BinarySearchTree::insert(BinaryNode* &pNode,int value) { if(pNode==NULL) { BinaryNode*pBSTree=new BinaryNode(value,NULL,NULL); pNode=pBSTree; if(root==NULL) root=pBSTree;//根节点 } else { if(pNode->element>value) { insert(pNode->leftChild,value); } else if(pNode->element<value) { insert(pNode->rightChild,value); } else { //相等什么都不做 } } } */ BinaryNode* BinarySearchTree::find(int x,BinaryNode*t) const { if(t==NULL) return NULL; if(t->element>x) find(x,t->leftChild); else if(t->element<x) find(x,t->rightChild); else return t; } BinaryNode* BinarySearchTree::findMax(BinaryNode* t) const { while(t->rightChild!=NULL) { t=t->rightChild; } return t; } BinaryNode* BinarySearchTree::findMin(BinaryNode*t) const { while(t->leftChild!=NULL) { t=t->leftChild; } return t; } void BinarySearchTree::insert(int x,BinaryNode*&t) { if(t==NULL) t=new BinaryNode(x,NULL,NULL); else if(t->element>x) insert(x,t->leftChild); else if(t->element<x) insert(x,t->rightChild); else { cout<<"元素重复"<<endl; return; } } void BinarySearchTree::remove(int x,BinaryNode*&t) { if(t==NULL) { cout<<"不存在此节点"<<endl; return; } if(t->element>x) //1 找到要删除的节点 remove(x,t->leftChild); else if(t->element<x) remove(x,t->rightChild); else { if(t->leftChild!=NULL&&t->rightChild!=NULL) //左右子节点都有时 { t->element=findMin(t->rightChild)->element;//2 查找右侧最小节点做替换 removeMin(t->rightChild); } else //只有一个节点时 { BinaryNode*temp=t; t=(t->leftChild!=NULL)?t->leftChild:t->rightChild; delete temp; } } } void BinarySearchTree::removeMin(BinaryNode*&t) { if(t==NULL) { cout<<"节点为空"<<endl; return; } else if(t->leftChild!=NULL) // 这种情况不可能,但是为了考虑问题的完整型,还是做个判断吧!O(∩_∩)O~ { removeMin(t->leftChild); } else if(t->leftChild==NULL) { BinaryNode*tmp=NULL; t=t->rightChild; //因为是最小节点t->rightChild一定等于NULL delete tmp; } } int main() { BinaryNode*pNode=NULL; BinarySearchTree*pbst=new BinarySearchTree(pNode); pbst->insert(21,pNode); pbst->insert(12,pNode); pbst->insert(0,pNode); pbst->insert(15,pNode); pbst->insert(35,pNode); pbst->insert(14,pNode); pbst->insert(36,pNode); cout<<"****最大值****"<<endl; cout<<(pbst->findMax(pNode))->element<<endl; cout<<"****最小值****"<<endl; cout<<(pbst->findMin(pNode))->element<<endl; }