以下是二叉树的插入,生成和遍例程序.编译无误,但执行时是非法操作.大家帮忙看看问题在哪?谢谢各位!
#include <iostream.h>
typedef int datatype;
struct node { datatype data; node *lchild,*rchild; };
// Insert keyword to bintree void Ibtree( node *root,datatype key ) { if( root == NULL ) { node *root = new node; root->data = key; root->lchild = root->rchild =NULL; } else if ( root->data == key ) return; else if ( root->data<key ) Ibtree( root->lchild,key ); else Ibtree( root->rchild,key ); }
// Great bintree node* Gbtree( datatype a[],int n ) // n is the length of the array a { node *root = new node; root = NULL; for( int i=0; i<=n-1; i++ ) { Ibtree( root,a[i] ); } return root; //return the root of the tree }
// Show bintree void Sbtree( node *root ) { if ( root->lchild != NULL ) Sbtree( root->lchild ); cout<< root->data <<endl; if ( root->rchild != NULL ) Sbtree( root->rchild ); }
void main() { datatype a[3] = {9,5,10}; node *root = Gbtree( a,3 ); Sbtree( root ); }