poj 2255 二叉树的建立和遍历

//http://acm.pku.edu.cn/JudgeOnline/problem?id=2255
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
char preorder[30];
char inorder[30];
typedef struct _node
{
    char val;   
    struct _node *left;
    struct _node *right;
}node;
struct _node* root;
struct _node* mk_tree(char *pre,char *in,int n) //递归建树,注意返回的是节点指针
{
    struct _node* r=NULL;
    if(n>0)
    {
        r=(struct _node*)malloc(sizeof(struct _node));
        r->val=*pre;
        int i;
        char *p=in;
        for(i=0;i<n;i++,p++)
            if(*p==*pre)break;

        r->left=mk_tree(pre+1,in,i);
        r->right=mk_tree(pre+i+1,in+i+1,n-i-1);   
    }
    return r;
}

void postorder(struct _node* r) //后根遍历
{
   
    if(r==NULL)return;
    postorder(r->left);   
    postorder(r->right);
    printf("%c",r->val);

}

int main()
{
    while(cin>>preorder>>inorder)       
    {
        struct _node* root=mk_tree(preorder,inorder,strlen(preorder));
        postorder(root);
        printf("/n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值