问题一 根据后序和中序遍历输出先序遍历
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder:
以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
代码如下:
#include<iostream>
using namespace std;
int l[31], m[31];
typedef struct node
{
int data;
struct node *left, *right;
}bintree;
bintree *tree(int n, int *m, int *l);
void first(bintree *root);
int main()
{
int N;
bintree *root = NULL;
cin >> N;
for (int i = 0; i <N; i++)
cin >> l[i];
for (int i = 0; i < N; i++)
cin >> m[i];
root = tree(N, m, l);
cout << "Preorder:";
first(root);
cout << endl;
system("pause");
return 0;
}
bintree *tree(int n, int *m, int *l)
{
int i;
bintree *root = NULL;
if (n <= 0) return NULL;
root = (bintree*)malloc(sizeof(bintree));
root->data = l[n - 1];//放入根节点数据
root->left = root->right = NULL;
for (i = 0; i < n; i++)
if (root->data == m[i])
break;//找到中序中与后序对应的数字并记下位置
root->left = tree(i, m, l);
root->right = tree(n - i - 1, m + i + 1, l + i);//右边的序列在中序中是从i+1开始的,在后序中是从i开始的
return root;
}
void first(bintree *root)
{
if (root)
{
cout << ' ' << root->data;
first(root->left);
first(root->right);
}
}//先中后序遍历对应输出的位置
问题二 层序遍历
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
层序遍历代码如下:
int x = 0;
void print(bintree *root)
{
queue<bintree *> q;
q.push(root);//新建一个队列并将树push 进去
while (!q.empty())
{
++x;
bintree *front = q.front();//让树指向队列最前面的节点
if (x == 1) cout << front->data;
else cout << " "<<front->data;
q.pop();//删除最前面的节点
if (front->left)
q.push(front->left);//判断最前面的左节点是否为空,不是则放入队列
if (front->right)
q.push(front->right);//判断最前面的右节点是否为空,不是则放入队列
}
}//注意加一个头文件#include<queue>
问题三还原二叉树
代码如下:
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
#include<iostream>
using namespace std;
char f[51], m[51];
typedef struct node
{
char data;
struct node *left, *right;
}bintree;
bintree *tree(int n, char *m, char *l);
int height(bintree *root);
int main()
{
int N, h;
bintree *root = NULL;
cin >> N;
for (int i = 0; i <N; i++)
cin >> f[i];
for (int i = 0; i < N; i++)
cin >> m[i];
root = tree(N, m, f);
h = height(root);
cout << h << endl;
system("pause");
return 0;
}
bintree *tree(int n, char *m, char *f)
{
int i;
bintree *root = NULL;
if (n <= 0) return NULL;
root = (bintree*)malloc(sizeof(bintree));
root->data = f[0];
root->left = root->right = NULL;
for (i = 0; i < n; i++)
if (root->data == m[i])
break;
root->left = tree(i, m, f + 1);//先序向后移一位
root->right = tree(n - i - 1, m + i + 1, f + i + 1);//位于右边的序列在中序和先序中都是从i+1开始的
return root;
}
int height(bintree *root)
{
int max, hl, hr;
if (root)
{
hl = height(root->left);
hr = height(root->right);
max = hl > hr ? hl : hr;
return (max + 1);
}
else return 0;
}