二叉树的创建与遍历:
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; char *str=""; //二叉树结点的定义 typedef struct BTNode { char data; struct BTNode *lc; struct BTNode *rc; }BTNode,*BiTree; void Creat(BiTree &T) { char ch[2]; scanf("%s",&ch[0]); //cin.get(ch); if(strcmp(ch,"@")==0) T=NULL; else{ T=new BTNode; T->data=ch[0]; Creat(T->lc); Creat(T->rc); } } //先序遍历 void PreOrder(BiTree T) { if(T) { cout<<T->data<<' '; PreOrder(T->lc); PreOrder(T->rc); } } //中序遍历 void InOrder(BiTree T) { if(T) { InOrder(T->lc); cout<<T->data<<' '; InOrder(T->rc); } } //后序遍历 void PostOrder(BiTree T) { if(T) { PostOrder(T->lc); PostOrder(T->rc); cout<<T->data<<' '; } } int main() { int c; BiTree T; printf("Input nodes of binary tree:(NULL<=>'@')\n"); Creat(T); while(1) { cout<<"\nPlease select a service:\n"; cout<<"\n1:PreOrder Traverse\n2:InOrder Traverse\n3:PostOrder Traverse\n0:Exit\n"; cin>>c; switch(c) { case 1:{cout<<"\nPreOrder traverse:\n"; PreOrder(T); break;} case 2:{cout<<"\nInOrder traverse:\n";InOrder(T);break;} case 3:{cout<<"\nPostOrder traverse:\n";PostOrder(T);break;} default:{cout<<"Game Over!\n";return 0;} } } }