1138 Postorder Traversal

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

题意:

  给出一棵二叉树的前序遍历和中序遍历,求后序遍历的第一个数字。

思路:

  由前序遍历的结果找出根节点(找子树根节点的过程需要借助中序遍历来确定左右子树的结点数目),root,表示当前根节点,[]star,end]表示当前树的结点在中序遍历结果中的开始和结束下标。

  后序遍历的输出顺序是“左 右 根”,所以如果有左子树,那么后序遍历的第一个数字一定在左子树中,如果没有左子树有右子树,那么一定在右子树里,要是既没有左子树,有没有右子树,那么,该结点就是所要查找的。

Code:

#include <bits/stdc++.h>

using namespace std;

vector<int> preOrder;
vector<int> inOrder;
bool found = false;

void buildTree(int root, int start, int end) {
    if (start > end) return;
    int i = start;
    while (i <= end && inOrder[i] != preOrder[root]) ++i;
    int len = i - start;
    buildTree(root + 1, start, i - 1);
    buildTree(root + len + 1, i + 1, end);
    if (!found) {
        cout << inOrder[i] << endl;
        found = true;
    }
}

int main() {
    int n;
    cin >> n;
    preOrder = vector<int>(n);
    inOrder = vector<int>(n);
    for (int i = 0; i < n; ++i) cin >> preOrder[i];
    for (int i = 0; i < n; ++i) cin >> inOrder[i];
    buildTree(0, 0, n - 1);
    return 0;
}

  

本来以为会很简单,但是自己做的时候,因为受到了之前做的题目的影响,想着先建树再遍历来做(而且自己建树的方法也比笨)最后提交的时候两组数据超时了。

永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/12709827.html