PAT甲级-1138 Postorder Traversal

    xiaoxiao2022-07-13  142

    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

    题意 根据给出的二叉树的前序与中序得到后序的第一个节点

    #include<bits/stdc++.h> #define maxn 50001 using namespace std; struct tree{ int data; struct tree*left,*right; }; int pre[maxn],in[maxn],flag; vector<int>v; void buildTree(tree**t,int preL,int preR,int inL,int inR) { if(preL>preR) return; int rootVal=pre[preL]; int rootIndex=inL; while(rootVal!=in[rootIndex]) rootIndex++; (*t)=(tree*)malloc(sizeof(tree)); (*t)->data=rootVal; (*t)->left=(*t)->right=NULL; buildTree(&(*t)->left,preL+1,preL+rootIndex-inL,inL,rootIndex-1); buildTree(&(*t)->right,preL+rootIndex-inL+1,preR,rootIndex+1,inR); } void findPostOrder(tree*t) { if(t==NULL) return; findPostOrder(t->left); findPostOrder(t->right); v.push_back(t->data); } int main() { int n; cin >> n; for(int i=0;i<n;i++) cin >> pre[i]; for(int i=0;i<n;i++) cin >> in[i]; tree*root; root=NULL; buildTree(&root,0,n-1,0,n-1); findPostOrder(root); cout << v[0]; }
    最新回复(0)