1020. Tree Traversals (25)

来源:互联网 发布:21lic单片机项目外包网 编辑:程序博客网 时间:2024/06/05 14:46

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:
72 3 1 5 7 6 41 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

    先建立树,再BFS输出。

#include <iostream>#include <cstdio>#include <vector>#include <algorithm>#include <queue>using namespace std;struct Node{int val;Node* left;Node* right;Node(int val) : val(val), left(nullptr), right(nullptr){}};template<typename Iter>Node* build(Iter inBegin, Iter inEnd, Iter postBegin, Iter postEnd){if(inBegin == inEnd) return nullptr;if(postBegin == postEnd) return nullptr;const auto val = *prev(postEnd);Node* root = new Node(val);auto inRootPos = find(inBegin, inEnd, val);auto sizeLeft = distance(inBegin, inRootPos);auto postLeftEnd = next(postBegin, sizeLeft);root->left = build(inBegin, inRootPos, postBegin, postLeftEnd);root->right = build(next(inRootPos), inEnd, postLeftEnd, prev(postEnd));return root;}int main(){int n;scanf("%d", &n);vector<int> post(n);vector<int> inorder(n);for(int i = 0; i < n; ++i)scanf("%d", &post[i]);for(int i = 0; i < n; ++i)scanf("%d", &inorder[i]);auto tree = build(begin(inorder), end(inorder), begin(post), end(post));queue<Node*> Q;if(tree) Q.push(tree);bool first = true;while(!Q.empty()){Node* root = Q.front();Q.pop();if(root->left) Q.push(root->left);if(root->right) Q.push(root->right);if(first) first = false;else printf(" ");printf("%d", root->val);}return 0;}


0 0
原创粉丝点击