zcmu 4931: 二叉树遍历

题目链接:

#include<cstdio>
#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
#include<cmath>
#include<cstring>
using namespace std;
char pre[30],in[30];
struct node{
    char data;
    node* lchild;
    node* rchild;
}Node[26];
node* create(int preL,int preR,int inL,int inR)
{
    if(preL>preR)
        return NULL;//条件忘记了
    node* root=new node;
    root->data=pre[preL];
    int k;
    for(k=inL;k<=inR;k++)
    {
        if(in[k]==pre[preL])
        {
            break;
        }
    }
    int numL=k-inL;
    root->lchild=create(preL+1,preL+numL,inL,k-1);
    root->rchild=create(preL+1+numL,preR,k+1,inR);
    return root;
}
void postorder(node* root)
{
    if(root==NULL)
        return;
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%c",root->data);
}
int main()
{
    while(gets(pre))
    {
    gets(in);
    int len=strlen(pre);
    node* root=create(0,len-1,0,len-1);
    postorder(root);
    printf("\n");
    }
    return 0;
}

一道常规的二叉树遍历

首先给出两个遍历过程

可以求出这个树

其次

要知道先序、后序、中序遍历的代码

猜你喜欢

转载自blog.csdn.net/qq_42232118/article/details/82533410