[PAT-甲级]1020.Tree Traversals

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

解题思路:根据二叉树的后序和中序序列来建树,并打印这颗二叉树的层序遍历。递归的去建树。后序最后一个节点是根节点,该根节点将中序序列分为左右子树两部分。递归去做。

代码如下:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>

using namespace std;

struct Node
{
	int data;
	Node* leftChild;
	Node* rightChild;
};

int in[32], post[32];
vector<int> level;

Node* create(int postL, int postR, int inL, int inR)
{
	if(postL > postR)
		return NULL;
	
	Node* root = new Node;
	root->data = post[postR];
	
	int k;
	for(k = inL; k <= inR; k ++)
	{
		if(in[k] == post[postR])
			break;
	}
	
	int countLeft = k - inL;
	
	root->leftChild = create(postL, postL+countLeft-1, inL, k-1);
	root->rightChild = create(postL+countLeft, postR-1, k+1, inR);
	
	return root;
}

void BFS(Node* root)
{
	queue<Node*> que;
	que.push(root);
	
	while(!que.empty())
	{
		Node *pre = que.front();
		que.pop();
		level.push_back(pre->data);
		
		if(pre->leftChild != NULL)
			que.push(pre->leftChild);
		if(pre->rightChild != NULL)
			que.push(pre->rightChild);
	}
}

int main()
{
	freopen("D://input.txt", "r", stdin);
	int n;
	scanf("%d", &n);
	
	for(int i = 0; i < n; i ++)
		scanf("%d", &post[i]);
		
	for(int i = 0; i < n; i ++)
		scanf("%d", &in[i]);
	
	Node* root = create(0, n-1, 0, n-1);
	BFS(root);
	
	
	for(int i = 0; i < level.size(); i ++)
	{
		if(i == 0)
			printf("%d", level[i]);
		else
			printf(" %d", level[i]);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/74912093