九度OJ-1078 二叉树遍历




思路:

1.将两个遍历结果分别存入两个字符数组中


struct Node{
    Node* lchild;
    Node* rchild;
    char c;
}tree[50];

int size = 0;
char a[50],b[50];
Node* create()
{
    tree[size].lchild=tree[size].rchild=NULL;
    return &tree[size++];
}


2.后序遍历的实现


void postorder(Node *r)
{
    if (r==NULL) {
        return ;
    }
    postorder(r->lchild);
    postorder(r->rchild);
    cout<<r->c;
}


3.递归的方式还原树


Node* build(int b1,int e1,int b2,int e2)
{
    Node *ret = create();
    ret->c=a[b1];
    int index;
    for (int i=b2; i<=e2; i++) {
        if (a[b1]==b[i]) {
            index=i;
            break;
        }
    }
    if (index!=b2) {  //左子树非空
        ret->lchild=build(b1+1, b1+index-b2, b2, index-1);
    }
    if (index!=e2) {  //右子树非空
        ret->rchild=build(b1+index-b2+1, e1, index+1, e2);
    }
    return ret;
}


4.主函数形式


int main()
{
    while (cin>>a) {
        cin>>b;
        Node *root = build(0,strlen(a)-1,0,strlen(b)-1);
        postorder(root);
        cout<<endl;
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值