Binary search tree
Refers to a binary search tree when inserting data, compare the root node, the size of the tree to find into the ordered position and stored.
Implementation
Data into the tree, compared to the root of the tree, big words on the left (on the right), small words on the right (left).
#include <the iostream> #include <Vector> the using namespace STD; typedef struct Std { int iNum; struct Std * left; struct Std * right; } Tree; Vector <Vector < int >> prder; // to traverse the level / / a, create an empty tree tree CreateTree * ( int iNumroot); // Second, insert data void InsertTree (tree Head *, int n-); // Third, the delete node tree * the delete (tree Head *, int n-); //Fourth, traverse the level Vector <Vector < int >> Layer_Tree (Tree * Head); void layertree (Tree Head *, int n-); // IV.2, output data void Point (); int main () { Tree * the root ; int iNumroot; int iNumber; // input roots COUT << " input roots: " << endl; CIN >> iNumroot; the root = CreateTree (iNumroot); // input data number COUT << " input data number: "<< endl; CIN >> iNumber; COUT << " input data: " ; for ( int I = 0 ; I <iNumber; I ++ ) { int A; CIN >> A; InsertTree (the root, A); } // remove node COUT << " input node to be removed: " ; int m; CIN >> m; the root = the delete (the root, m); // level output data prder = Layer_Tree (the root); Point (); return 0; } Tree* CreateTree(int iNumroot) { Tree* Head; Head=new Tree; (*Head).iNum=iNumroot; Head->left=NULL; Head->right=NULL; return Head; } void InsertTree(Tree* Head,int n) { if(n>Head->iNum) { if(Head->right) { InsertTree(Head->right,n); } else { Tree* New=new Tree; (*New).iNum=n; New->left=NULL; New->right=NULL; Head->right=New; return; } } else { if(Head->left) { InsertTree(Head->left,n); } else { Tree* New=new Tree; (*New).iNum=n; New->left=NULL; New->right=NULL; Head->left=New; return; } } } vector<vector<int> > Layer_Tree(Tree* Head) { if(!Head) return prder; layertree(Head,0); return prder; } Tree* Delete(Tree* Head,int n) { if(!Head) { cout<<"删除的节点不存在!"<<endl; } if(n==Head->iNum) { if(Head->left&&Head->right) { Tree* cur=Head->right; while(cur->iNum!=NULL) { cur=cur->left; } Head->iNum=cur->iNum; Head->right=Delete(Head->right,cur->iNum); } else if(!Head->left&&!Head->right) { return NULL; } else { Head=(Head->left==NULL)?Head->right:Head->left; } } else if(n>Head->iNum) { Head->right=Delete(Head->right,n); } else { Head->left=Delete(Head->left,n); } return Head; } void layertree(Tree* Head,int n) { if(!Head) return; if(n>=prder.size()) { vector<int> x; prder.push_back(x); } prder[n].push_back(Head->iNum); layertree(Head->left,n+1); layertree(Head->right,n+1); } void Point() { for(int i=0;i<prder.size();i++) { if(prder[i].empty()) { cout<<"N"<<" "; } for(int j=0;j<prder[i].size();j++) { cout<<prder[i][j]<<" "; } cout<<endl; } }