1. 程式人生 > >二叉樹按層輸入及先序輸入,及三種輸出

二叉樹按層輸入及先序輸入,及三種輸出

二叉樹的指標和地址看的真難受,各種問題。
*&

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "string.h"
#define num 100
using namespace std;
typedef char datatype;
typedef struct  BinTNode{
     BinTNode *lchild;
     BinTNode *rchild;
    char data;
}BinTNode,*BinTree;

//按層輸入 [email protected]
@[email protected]@E#
void CreateBinTree(BinTree &bt) { BinTNode *Q[num]; BinTNode *s; int parent,child; char ch; ch=getchar(); bt=NULL; parent=1; child=0; while(ch!='#') { s=NULL; child++; if(ch!='@') { s= new BinTNode(); s->data=ch; s->
lchild=s->rchild=NULL; } Q[child]=s; if(child==1) bt=s; else if(s&&child>0) { parent=child/2; if(child%2==0) Q[parent]->lchild=s; else Q[parent]->rchild=s; } ch=getchar(); } } //先序輸入 AB#DE###C#F##
void createBiTree(BinTree &T) { char c; cin >> c; if('#' == c) T = NULL; else { T = new BinTNode; T->data=c; createBiTree(T->lchild); createBiTree(T->rchild); } } void PreorderTraversal(BinTree T) { if(T==NULL) return; cout<<T->data<<" "; PreorderTraversal(T->lchild); PreorderTraversal(T->rchild); } void InOrderTraveres(BinTree T) { if(T == NULL) return; InOrderTraveres(T -> lchild); cout<<T->data<<" "; InOrderTraveres(T -> rchild); } void PostTraversing(BinTree T) { //cout<<" dsa"<<endl; if(T == NULL) return; PostTraversing(T -> lchild ); PostTraversing(T -> rchild); cout<<T->data<<" "; } int main () { //freopen("66.txt","r",stdin); BinTree T,S; cout<<"按層輸入:"<<endl; CreateBinTree(T); cout<<"先序輸出:"; PreorderTraversal(T); cout<<endl<<"中序輸出:"; InOrderTraveres(T); cout<<endl<<"後序輸出:"; PostTraversing(T); cout<<endl<<endl; cout<<"先序輸入:"<<endl; createBiTree(S); cout<<"先序輸出:"; PreorderTraversal(S); cout<<endl<<"中序輸出:"; InOrderTraveres(S); cout<<endl<<"後序輸出:"; PostTraversing(S); return 0; }