cpp代码实现
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
typedef struct BiNode
{
int data;
BiNode* lchild;
BiNode* rchild;
}Bitree;
void Bitree_creat(Bitree* fa,int u)
{
if(u > n) return;
Bitree* l = new(BiNode);
Bitree* r = new(BiNode);
cin >> (fa->data);
fa -> lchild = l;
fa -> rchild = r;
//cout << "Yes" << endl;
// cout << (fa ->data) << endl;
Bitree_creat(fa ->lchild,2*u);
Bitree_creat(fa ->rchild,2*u+1);
return;
}
void Bitree_pr_pr(Bitree* fa,int u)
{
if(u > n)return;
//cout << "YES" << endl;
cout << (fa ->data) << ' ';
Bitree_pr_pr(fa ->lchild,u*2);
Bitree_pr_pr(fa ->rchild,u*2+1);
return;
}
void Bitree_center_pr(Bitree* fa,int u)
{
if(u > n)return;
Bitree_center_pr(fa ->lchild,u * 2);
cout << (fa -> data) << ' ';
Bitree_center_pr(fa ->rchild,u * 2 + 1);
return;
}
void Bitree_en_pr(Bitree* fa,int u)
{
if(u > n)return;
Bitree_en_pr(fa ->lchild,u * 2);
Bitree_en_pr(fa ->rchild,u * 2 + 1);
cout << (fa -> data) << ' ';
return;
}
int main()
{
Bitree* T;T = new(BiNode);
cin >> n;
Bitree_creat(T,1);
cout << "先序建立二叉树完成!" << endl;
cout << "先序遍历:"<< endl;
Bitree_pr_pr(T,1);
cout << endl;
cout << "中序遍历:"<< endl;
Bitree_center_pr(T,1);
cout << endl;
cout << "后序遍历:"<< endl;
Bitree_en_pr(T,1);
cout << endl;
}
测试数据
20
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
运行结果