# 树的遍历问题

### 输入样例:

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>

### 输入样例:

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;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120