/*建立二叉樹,輸出其各種遍歷結果。*/
#include<iostream>
#include<malloc.h>
#include <stdlib.h>
using namespace std;
#define NULL 0
/*二叉樹的二叉鏈表結點結構定義*/
typedef struct node{
char value;//結點資料
struct node *lChild;//左孩子指標
struct node *rChild;//右孩子指標
}BiTree,*BT;
/*生成一顆二叉樹*/
void InsertBST(BT *t,int key)
{
BiTree *s;
int is=-1;
if(*t==NULL){
s=(BT)malloc(sizeof(BT));
s->value=https://bbs.csdn.net/topics/key;
s->lChild=NULL;
s->rChild=NULL;
*t=s;
}else{
if(is==-1){
(*t)->value=https://bbs.csdn.net/topics/key;//生成根結點
is=1;
InsertBST(&((*t)->lChild),key);//遞回,構造左子樹
}else{
(*t)->value=https://bbs.csdn.net/topics/key;//生成根結點
is=-1;
InsertBST(&((*t)->rChild),key);//遞回,構造右子樹
}
}
}
void CreateBST(BT *t) //創建二叉排序樹
{//輸入一個結點序列,建立一顆二叉排序樹,將根結點指標回傳
int key;
*t=NULL;
scanf("%d",&key);
while(key)
{
InsertBST(t,key);
scanf("%d",&key);
}
}
/*二叉樹前序遍歷*/
int PreOrder(BT t){
if(t!=NULL){
printf("%c ",t->value);//列印資料結點
PreOrder(t->lChild);//先遍歷左子樹
PreOrder(t->rChild);//再遍歷右子樹
}
return 1;
}
/*二叉樹中序遍歷*/
int InOrder(BT t){
if(t!=NULL){
InOrder(t->lChild);//先遍歷左子樹
printf("%c ",t->value);//列印資料結點
InOrder(t->rChild);//再遍歷右子樹
}
return 1;
}
/*二叉樹后序遍歷*/
int PostOrder(BT t){
if(t!=NULL){
PostOrder(t->lChild);//先遍歷左子樹
PostOrder(t->rChild);//再遍歷右子樹
printf("%c ",t->value);//列印資料結點
}
return 1;
}
void main(){
BiTree *t=(BT)malloc(sizeof(BiTree));
printf("請輸入二叉樹:");
CreateBST(&t);
printf("前序遍歷二叉樹的結果為:");
PreOrder(t);
printf("\n");
printf("中序遍歷二叉樹的結果為:");
InOrder(t);
printf("\n");
printf("后序遍歷二叉樹的結果為:");
PostOrder(t);
printf("\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/58960.html
標籤:基礎類
