题目1078:二叉树遍历

此题涉及到二叉树的遍历以及二叉树的建立

#include <iostream>
#include <string>

using namespace std;

struct Node           //定义树的结点
{
    Node *lchild;
    Node *rchild;
    char c;
};
Node Tree[50];        //结点数组

string str1,str2;

void postOrder(Node *T)
{
    if (T->lchild != NULL)
    {
        postOrder(T->lchild);
    }
    if (T->rchild != NULL)
    {
        postOrder(T->rchild);
    }
    cout << T->c;
}
int local;

Node* creat()        //从结点数组中拿出一个结点进行初始化后,返回它的地址
{
    Tree[local].lchild = Tree[local].rchild = NULL;
    local++;
    return &Tree[local-1];
}

Node* build(int s1,int e1,int s2,int e2)    //建树函数
{
    Node* ret = creat();               //为每次递归的根结点申请空间,并进行初始化
    ret->c = str1[s1];               //找到前序遍历的第一个结点
    int idx = str2.find(str1[s1]);     //找到前序遍历根结点字符在中序遍历中的位置
    if (idx != s2)      //若左子树不为空,递归还原左子树
    {
        ret->lchild = build(s1+1,s1+(idx-s2),s2,idx-1);
    }
    if (idx != e2)      //若右子树不为空,递归还原右子树
    {
        ret->rchild = build(s1+(idx-s2)+1,e1,idx+1,e2);
    }
    return ret;
}

int main()
{
    while (cin >> str1 >> str2)
    {
        int len1 = str1.size();
        int len2 = str2.size();
        local = 0;                  //确保对每个测试用例结点数组中的元素会重新初始化
        Node* T = build(0,len1-1,0,len2-1);   //建树
        postOrder(T);                          //后序遍历
        cout << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值