先序建立二叉樹,遞迴輸出二叉樹
阿新 • • 發佈:2018-12-20
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(){
char ch;
scanf("%c" ,&ch);
if(ch=='#')
return NULL;
BinTree T;
T=(BinTree)malloc(sizeof(struct TNode));
T->Data=ch;
T->Left=CreatBinTree();
T->Right=CreatBinTree();
return T;
}
//先序
void PreorderTraversal( BinTree BT ){
if(BT){
cout<<BT->Data;
PreorderTraversal(BT->Left);
PreorderTraversal (BT->Right);
}
}
//中序
void InorderTraversal( BinTree BT ){
if(BT){
InorderTraversal(BT->Left);
cout<<BT->Data;
InorderTraversal(BT->Right);
}
}
//後序
void PostorderTraversal( BinTree BT ){
if(BT){
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
cout<< BT->Data;
}
}
int main()
{
BinTree BT=CreatBinTree();
PreorderTraversal(BT);
cout<<endl;
InorderTraversal(BT);
cout<<endl;
PostorderTraversal(BT);
cout<<endl;
return 0;
}