您的位置:首页 > 其它

1020. Tree Traversals (25) - 已知后序和中序求二叉树

2015-08-13 20:50 309 查看
1020. Tree Traversals (25)题目地址

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7

2 3 1 5 7 6 4

1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

已知二叉树的后序 和 中序 遍历 求层次遍历

基本上 熟练的话 15分钟-20分钟AC这类问题

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>

using namespace std;

#define N 31

int n;

int post
; // 后
int in
; // 中

typedef struct node{
int data;
struct node* left;
struct node* right;
node(int _data = -1) :data(_data), left(NULL), right(NULL){}
}Bnode;

Bnode* root;

Bnode* createTree(int postL, int postR, int inL, int inR)
{
if (postL > postR)
{
return NULL;
}
int data = post[postR];
int pos = 0;
while (in[pos] != data)
{
pos++;
}

Bnode* bt = new Bnode(data);
bt->left = createTree(postL, postL + pos - inL - 1, inL, pos-1);
bt->right = createTree(postL + pos - inL, postR - 1, pos + 1, inR);
return bt;
}

void levelorder(Bnode* root)
{
queue<Bnode*> que;
while (!que.empty())
{
que.pop();
}
que.push(root);
bool flag = true;
while (!que.empty())
{
Bnode* bt = que.front();
que.pop();
if (flag)
{
printf("%d", bt->data);
flag = false;
}
else{
printf(" %d", bt->data);
}
if (bt->left != NULL)
{
que.push(bt->left);
}
if (bt->right != NULL)
{
que.push(bt->right);
}
}
}

int main()
{
//freopen("in", "r", stdin);
while (scanf("%d", &n) != EOF)
{
int i;
for (i = 0; i < n; i++)
{
scanf("%d", &post[i]);
}
for (i = 0; i < n; i++)
{
scanf("%d", &in[i]);
}
root = NULL;

root = createTree(0, n - 1, 0, n - 1);
levelorder(root);
printf("\n");
}
return 0;
}
/*
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

4 1 6 3 5 7 2
*/


总结: 先序和中序 ; 后序和中序 ; 可以求出二叉树,就是个递归建树的过程 要注意递归参数,调试时可以一步步看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: