1138 Postorder Traversal (25 point(s))
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder 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 (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder 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 first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
根据前序遍历和中序遍历给出后序遍历。
注意点:
1. C++11引入nullptr作为空指针。C++11以下支持NULL(视为0)。尽量使用nullptr。
2. createTree()的本质是根据前序遍历中root位置是根,而中序遍历是按照左子树、根、右子树的顺序。首先动态建立新的结点,然后新结点的左子树可以根据中序遍历的左边建立,右子树可以根据中序遍历的右边建立,只需要确定在中序遍历中根的位置即可。
3. createTree()注意终止条件(即某子树不存在,left>right,返回空指针nullptr)。
4. 注意返回当前根节点。
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
const int MAX = 5e4+7;
struct Node{
int data;Node* left;Node* right;
Node(int d):data(d),left(nullptr),right(nullptr){}
};
int pre[MAX],in[MAX];
Node* createTree(int root,int left,int right){
//前序遍历的root位置是根节点,根据中序的left到right区分左右子树
if(left>right) return nullptr;
Node* p = new Node(pre[root]);
int index = left;
while(in[index]!=pre[root]) index++;
p->left = createTree(root+1,left,index-1);
p->right = createTree(root+index-left+1,index+1,right);
return p;
}
vector<int> v;
void postOrder(Node* root){
if(root->left!=nullptr) postOrder(root->left);
if(root->right!=nullptr) postOrder(root->right);
v.push_back(root->data);
}
int N;
int main(void){
cin>>N;
for(int i=0;i<N;i++) cin>>pre[i];
for(int i=0;i<N;i++) cin>>in[i];
Node *root = nullptr;
root = createTree(0,0,N-1);
postOrder(root);
cout<<v[0]<<endl;
return 0;
}