二叉树遍历

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
struct treenode{
char data;
treenode *lchild;
treenode *rchild;
treenode(char c)
:data(c)
,lchild(NULL)
,rchild(NULL)
{

}
};

treenode *build(string str1,string str2)
{
    if(str1.size()==0)
    return NULL;
    char c=str1[0];
    treenode *root =new treenode(c);
    int position=str2.find(c);
    root->lchild=build(str1.substr(1,position),str2.substr(0,position));
    root->rchild=build(str1.substr(position+1),str2.substr(position+1));
    return root;

}

void postorder(treenode *root)
{
    if(root==NULL)
    return ;
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%c",root->data);
    return ;
}
int main()
{
    string str1;
    string str2;
    while(cin>>str1>>str2)
    {
        treenode *root=build(str1,str2);
        postorder(root);
        printf("\n");
    }
    return 0;
}
发布了29 篇原创文章 · 获赞 1 · 访问量 729
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览