1 条题解

  • 0
    @ 2022-12-8 21:28:47

    一步到位

    #include <bits/stdc++.h>
    using namespace std;
    string xian, zhong;
    // 把先序遍历为 xian[l..r] 中序遍历为 zhong[ll..rr] 的后续遍历输出
    void f(int l, int r, int ll, int rr)
    {
        //根节点下标,左子树大小,右子树大小
        int root, lLen, rLen;
        root = l;
        int pos; //根节点在中序遍历的位置
        for (int i = ll; i <= rr; i++)
            if (zhong[i] == xian[root])
                pos = i;
        lLen = pos - ll; //左子树大小 zhong[ll]~zhong[pos-1]
        rLen = rr - pos; //右子树大小 zhong[pos+1]~zhong[rr]
        // xian: root (l+1,l+lLen) (l+lLen+1,r)
        // zhong: (ll,pos-1) pos (pos+1,rr)
        if (lLen > 0)
            f(l + 1, l + lLen, ll, pos - 1); //把左子树后序遍历输出
        if (rLen > 0)
            f(l + lLen + 1, r, pos + 1, rr); //把右子树后序遍历输出
        cout << xian[root];                  //输出根
    }
    int main()
    {
        cin >> xian >> zhong;
        f(0, xian.size() - 1, 0, zhong.size() - 1);
        return 0;
    }
    

    先构建树,再输出

    #include <bits/stdc++.h>
    using namespace std;
    string xian, zhong;
    //树的储存,节点编号按照先序遍历的下标来 
    int root;
    int ls[105];
    int rs[105];
    // 构建一棵树 (节点编号按照先序遍历的下标来)
    // 先序遍历为 xian[l..r] 
    // 中序遍历为 zhong[ll..rr] 
    void f(int l, int r, int ll, int rr)
    {
        //根节点下标,左子树大小,右子树大小
        int root, lLen, rLen;
        root = l;
        int pos; //根节点在中序遍历的位置
        for (int i = ll; i <= rr; i++)
            if (zhong[i] == xian[root])
                pos = i;
        lLen = pos - ll; //左子树大小 zhong[ll]~zhong[pos-1]
        rLen = rr - pos; //右子树大小 zhong[pos+1]~zhong[rr]
        // xian: root (l+1,l+lLen) (l+lLen+1,r)
        // zhong: (ll,pos-1) pos (pos+1,rr)
        if (lLen > 0){
            f(l + 1, l + lLen, ll, pos - 1); //把左子树后序遍历输出
    		ls[l] = l + 1;
    	}
    	if (rLen > 0)
    	{
    		f(l + lLen + 1, r, pos + 1, rr); //把右子树后序遍历输出
    		rs[l] = l + lLen + 1;
    	}
    }
    void hou(int now)
    {
    	if(now==-1)
    		return;
    	hou(ls[now]);
    	hou(rs[now]);
    	cout<<xian[now];	
    } 
    int main()
    {
        cin >> xian >> zhong;
        memset(ls,-1,sizeof(ls));
        memset(rs,-1,sizeof(rs));
    	f(0, xian.size() - 1, 0, zhong.size() - 1);
        hou(0); 
    	return 0;
    }
    
    • 1

    信息

    ID
    558
    时间
    1000ms
    内存
    128MiB
    难度
    4
    标签
    (无)
    递交数
    65
    已通过
    32
    上传者