HDU 1710 Binary Tree Traversals 二叉树

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1710

题意:给定二叉树的先序和中序遍历序列,然后求后序遍历

思路:根据先序和中序遍历可以建二叉树,然后求后序遍历

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define bug puts("here")
using namespace std;

const int N = 1010;
int arr[N], brr[N], res[N];
int k;
struct node
{
    int v;
    node *lc, *rc;
    node(int v = 0, node *lc = NULL, node *rc = NULL):v(v), lc(lc), rc(rc){}
};
void dfs1(int l, int r, int &t, node* &root) //建树
{
    int flag = -1;
    for(int i = l; i <= r; i++)
        if(brr[i] == arr[t])
        {
            flag = i; break;
        }
    if(flag == -1) return;
    root = new node(brr[flag]);
    t++;
    if(flag > l)
        dfs1(l, flag - 1, t, root ->lc);
    if(flag < r)
        dfs1(flag + 1, r, t, root ->rc);
}
void dfs2(node *root)//求后序序列
{
    if(root != NULL)
    {
        dfs2(root ->lc);
        dfs2(root ->rc);
        res[k++] = root ->v;
    }
}
int main()
{
    int n;
    while(~ scanf("%d", &n))
    {
        for(int i = 1; i <= n; i++)
            scanf("%d", arr + i);
        for(int i = 1; i <= n; i++)
            scanf("%d", brr + i);
        node *root;
        int t = 1;
        dfs1(1, n, t, root);
        k = 0;
        dfs2(root);
        for(int i = 0; i < k; i++)
            printf("%d%c", res[i], i == k - 1 ? '\n':' ');
    }
    return 0;
}




你可能感兴趣的:(二叉树)