二叉查找数的操作:
1 #include <iostream> 2 3 using namespace std; 4 5 typedef struct BitNode 6 { 7 int data; 8 struct BitNode *lChild,*rChild; 9 }BitNode; 10 11 int main() 12 { 13 void InitTree(BitNode *&BitTree); 14 int PrintTree(BitNode *BitTree); 15 int SearchNode(BitNode *BitTree,int x); 16 int InsertNode(BitNode *&BitTree,int x); 17 int depthtree(BitNode *&BitTree); 18 BitNode *BitTree; 19 int dep=0; 20 BitTree=new BitNode; 21 InitTree(BitTree); 22 PrintTree(BitTree); 23 SearchNode(BitTree,4); 24 InsertNode(BitTree,5); 25 InsertNode(BitTree,6); 26 PrintTree(BitTree); 27 dep=depthtree(BitTree); 28 cout<<"二叉查找树的高度是:"<<dep<<endl; 29 return 0; 30 } 31 32 void InitTree(BitNode *&BitTree) 33 { 34 BitNode *pl,*pr; 35 BitTree->data=7; 36 pl=new BitNode; 37 pl->data=4; 38 pl->lChild=pl->rChild=NULL; 39 BitTree->lChild=pl; 40 pr=new BitNode; 41 pr->data=8; 42 pr->lChild=pr->rChild=NULL; 43 BitTree->rChild=pr; 44 } 45 46 int PrintTree(BitNode *BitTree) 47 { 48 if(BitTree) 49 { 50 cout<<BitTree->data<<endl; 51 PrintTree(BitTree->lChild); 52 PrintTree(BitTree->rChild); 53 } 54 return 0; 55 } 56 int SearchNode(BitNode *BitTree,int x) 57 { 58 while(BitTree) 59 { 60 if(BitTree->data==x) 61 { 62 cout<<"find x="<<x<<endl; 63 return 1; 64 } 65 if(x<BitTree->data) 66 BitTree=BitTree->lChild; 67 else 68 BitTree=BitTree->rChild; 69 } 70 cout<<"cannot find x="<<x<<endl; 71 return 0; 72 } 73 int InsertNode(BitNode *&BitTree,int x) 74 { 75 if(BitTree==NULL) 76 { 77 BitNode *p; 78 p=new BitNode; 79 p->data=x; 80 p->lChild=p->rChild=NULL; 81 BitTree=p; 82 cout<<"insert successfully"<<endl; 83 return 1; 84 } 85 else if(x<BitTree->data) 86 { 87 InsertNode(BitTree->lChild,x); 88 } 89 else 90 { 91 InsertNode(BitTree->rChild,x); 92 } 93 return 0; 94 } 95 96 int depthtree(BitNode *&BitTree) 97 { 98 int dr=0,dl=0; 99 if(BitTree==NULL) 100 return 0; 101 dr=1+depthtree(BitTree->rChild); 102 dl=1+depthtree(BitTree->lChild); 103 return dr>=dl?dr:dl; 104 }
共勉。