重建树

 

You have just finished a compiler design homework question where you had to find the parse tree of an expression. Unfortunately you left your assignment in the library, but luckily your friend picked it up for you. Instead of e-mailing you the parse tree so that you can rewrite the solution, your friend decides to play a practical joke and sends you just the DFS and BFS trace. Rather than try to redo the entire question you decide to reconstruct the tree.

Input

The input file contains several test cases as described below.

The first line of a input is the number n (1 <= n <= 1000) of nodes in the tree. The nodes in the tree are numbered 1, 2, ..., n. The remaining numbers are the BFS traversal followed by the DFS traversal. Note that when a parent was expanded the children were traversed in ascending order.

Output

The output for each case should consist of n lines, one for each node. Each line should start with the node number followed by a colon followed by a list of children in ascending order. If there is more than one solution, any correct answer is acceptable.

Sample Input

8
4 3 5 1 2 8 7 6
4 3 1 7 2 6 5 8

Sample Output

1: 7
2: 6
3: 1 2
4: 3 5
5: 8
6:
7:
8:

这道题其实和二叉树遍历那道题是差不多的,同样的方法,通过BFS序列得到根,再由这个根将DFS这一整棵树分成一块一块的子树。

不过二叉树遍历那道题使用链表的比较方便,那个链表也比较特殊,每个节点都有两个指向,然后整个链表又是单指向的。那道题主要通过递归的方法求,最后能得到一个表头指针,输出也会比较方便。
但是这道题如果得到一棵链表表示的树,输出会很不方便................
可以使用队列,做好每一个节点,这个节点的作用在于表示分块,l表示左,r表示右。然后通过根的位置来分块,每次都把该块入队列,只要队列不为空就不退出循环,这样每一个块都能有相应的处理了。
不过好像这样的过程也可以通过递归来实现。。。。。。

#include"iostream"
#include"queue"
#include"vector"
using namespace std;

const int maxn=1010;

struct node
{
    int l,r;
};

vector<int> ans[maxn];
queue<struct node> que;

int p;
int n;
int B[maxn];
int D[maxn];

void Build()
{
    int i;
    struct node c,e,t,m;
    c.l=0;
    c.r=n;
    que.push(c);
    while(!que.empty())
    {
        e=que.front();
        que.pop();

        if(e.r-e.l<=1)
            continue;

        int root=D[e.l];

        int pre=e.l+1;

        for(int i=pre;i<e.r;i++)
            if(D[i]==B[p])
            {
                t.l=pre;
                t.r=i;
                que.push(t);
                ans[root].push_back(D[i]);
                p++;
                pre=i;
            }
        if(e.r>pre)
        {
            m.l=pre;
            m.r=e.r;
            que.push(m);
        }

    }

}

int main()
{
    while(cin>>n&&n)
    {
        for(int i=0;i<n;i++)
            cin>>B[i];
        for(int i=0;i<n;i++)
            cin>>D[i];
        p=1;
        Build();
        for(int j=1;j<=n;j++)
        {
            cout<<j<<":";
            for(int k=0;k<ans[j].size();k++)
            {
            cout<<' ';
            cout<<ans[j][k];
            }
            cout<<endl;
           ans[j].clear();
        }

    }
    return 0;
}
原文地址:https://www.cnblogs.com/zsyacm666666/p/4671996.html