嘿嘿,不多言语,小道一篇,愿闻者入 诚可谓之经典的二叉排序树,常言道有树好乘凉~^—_—^||| #include <iostream.h>
struct tree { int data; tree *right,*left; };
class Btree { tree *root; public: Btree() { root=NULL; } void create_btree(int); void display() { inorder(root); cout<<endl; } void inorder( tree* ); };
void Btree::create_btree(int x) { tree *newnode=new tree; newnode->data=x; newnode->right=newnode->left=NULL; if(root==NULL) root=newnode; else { tree *back; tree *current=root; while(current!=NULL) { back=current; if(current->data>x) current=current->left; else current=current->right; } if(back->data>x) back->left=newnode; else back->right=newnode; } }
void Btree::inorder(tree *tmp) { if(tmp!=NULL) { inorder(tmp->left); cout<<tmp->data<< " "; inorder(tmp->right); } }
int main() { Btree A; int arr[]={7,4,1,5,12,8,13,11}; cout<<"建立排序二叉树顺序:"<<endl; for( int i=0 ; i<8 ; i++ ) { cout<<arr[i]<<" "; A.create_btree(arr[i]); } cout<<endl<<"中序遍历序列:"<<endl; A.display(); return 0; }
[此贴子已经被作者于2005-1-14 20:53:33编辑过]