函数题:确定二叉树(后序序列+中序序列)
要求实现函数,根据二叉树的后序序列和中序序列确定二叉树并返回指向二叉树根结点的指针。二叉树采用二叉链表存储,结点结构如下:
struct BiTNode { // 结点结构
int data; // 数据域
BiTNode *lchild,*rchild; // 左右孩子指针
BiTNode(int d,BiTNode *left,BiTNode *right) { // 构造函数
data=d;
lchild=left;
rchild=right;
}
};
### 函数接口定义:
c++
BiTNode* CreateBT(int* post, int *in, int n);
其中参数 post是指向后序序列数组首元素的指针, in是指向中序序列数组首元素的指针 ,n是结点总数。
### 裁判测试程序样例:
c++
#include<iostream>
using namespace std;
struct BiTNode { // 结点结构
int data; // 数据域
BiTNode *lchild,*rchild; // 左右孩子指针
BiTNode(int d,BiTNode *left,BiTNode *right) { // 构造函数
data=d;
lchild=left;
rchild=right;
}
};
void PreOrder(BiTNode* p, int &cnt) // 先序遍历
// 根据后序序列和中序序列确定二叉树,post是指向后序序列数组首元素的指针,in是指向中序序列数组首元素的指针 ,n是结点总数
BiTNode* CreateBT(int* post, int *in, int n);
// 根据后序序列和中序序列创建二叉树并先序遍历之
int main() {
int n;
while(cin>>n) {
int post[n], in[n], cnt=0;
for(int i=0; i<n; i++) cin>>post[i];
for(int i=0; i<n; i++) cin>>in[i];
BiTNode* root=CreateBT(post,in,n);
PreOrder(root, cnt);
cout<<endl;
}
return 0;
}
### 输入样例:
in
9
7 4 2 8 9 5 6 3 1
4 7 2 1 8 5 9 3 6
### 输出样例:
out
1 2 4 7 3 5 8 9 6
答案:若无答案欢迎评论
struct BiTNode { // 结点结构
int data; // 数据域
BiTNode *lchild,*rchild; // 左右孩子指针
BiTNode(int d,BiTNode *left,BiTNode *right) { // 构造函数
data=d;
lchild=left;
rchild=right;
}
};
### 函数接口定义:
c++
BiTNode* CreateBT(int* post, int *in, int n);
其中参数 post是指向后序序列数组首元素的指针, in是指向中序序列数组首元素的指针 ,n是结点总数。
### 裁判测试程序样例:
c++
#include<iostream>
using namespace std;
struct BiTNode { // 结点结构
int data; // 数据域
BiTNode *lchild,*rchild; // 左右孩子指针
BiTNode(int d,BiTNode *left,BiTNode *right) { // 构造函数
data=d;
lchild=left;
rchild=right;
}
};
void PreOrder(BiTNode* p, int &cnt) // 先序遍历
// 根据后序序列和中序序列确定二叉树,post是指向后序序列数组首元素的指针,in是指向中序序列数组首元素的指针 ,n是结点总数
BiTNode* CreateBT(int* post, int *in, int n);
// 根据后序序列和中序序列创建二叉树并先序遍历之
int main() {
int n;
while(cin>>n) {
int post[n], in[n], cnt=0;
for(int i=0; i<n; i++) cin>>post[i];
for(int i=0; i<n; i++) cin>>in[i];
BiTNode* root=CreateBT(post,in,n);
PreOrder(root, cnt);
cout<<endl;
}
return 0;
}
### 输入样例:
in
9
7 4 2 8 9 5 6 3 1
4 7 2 1 8 5 9 3 6
### 输出样例:
out
1 2 4 7 3 5 8 9 6
答案:若无答案欢迎评论