#include
#include
#include
#include
using namespace std;
typedef int elmtyp;
typedef struct BTnode{
elmtyp data; //数据域++默认为int
struct BTnode *lch,*rch;
}*BTree,BTnode;
BTree creat()
{
BTree root=NULL;
return root;
}
void insert(BTnode node,elmtyp elm)
{
if(node==NULL) node->data = elm;
else if(node->lch==NULL && node->rch ==NULL) node->data = elm;
else if(elm < node->data) //在其左子树
{
insert(node->lch,elm);
}
else if(elm > node->data) //在其右子树
{
insert(node->rch,elm);
}
else
{
return;
}
}
void preorder(BTnode node) //先序遍历
{
if(node==NULL) return;
printf("%d ",node->data);
preorder(node->lch);
preorder(node->rch);
}
void lastorder(BTnode node) //后序遍历
{
if(node==NULL) return;
lastorder(node->lch);
lastorder(node->rch);
printf("%d ",node->data);
}
int main()
{
bool end(false);
int cnt(0);
elmtyp data;
BTree root,rootbak;
root = creat();
while(!end)
{
printf("等待输入第%d个元素,如果输入结束请输入0回车\n",++cnt);
scanf("%d",&data);
if(data==0) end = true;
else
{
insert(*root,data);
}
}
printf("先序遍历\n");
preorder(*rootbak);
printf("\n");
printf("后序遍历\n");
lastorder(*rootbak);
printf("\n");
system("pause");
return 0;
} |