1. 程式人生 > >遞歸創建二叉樹

遞歸創建二叉樹

cout cin int 技術 node return tree postorder turn

1. 樹的存儲

typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;

2 .樹的創建

void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}

}

3.前序遍歷

void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}

4.中序遍歷

void PreOrder(BTree &T)
{
if(T)
{
PreOrder(T->lchild);

  cout<data;
PreOrder(T->rchild);
}
}

5.後序遍歷

void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);

cout<data;
}
}

6. 完整代碼

#include <stdlib.h>
#include
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;
void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;

CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BTree &T)
{
if(T!=NULL)
{
InOrder(T->lchild);
cout<data;
InOrder(T->rchild);
}

void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<data;
}
}
int main()
{
BTree T;
cout<<"請輸入樹的節點:" ;
CreateTree(T);
cout<<"先序遍歷:";
PreOrder(T) ;
cout<<endl;
cout<<"中序遍歷:";
InOrder(T) ;
cout<<endl;
cout<<"後序遍歷:";
PostOrder(T) ;
cout<<endl;
return 0;
}

7.輸入樣例

abd##e##cf###

8.運行截圖

技術分享圖片

遞歸創建二叉樹