题解 | #二叉树遍历#

二叉树遍历

http://www.nowcoder.com/practice/6e732a9632bc4d12b442469aed7fe9ce

#include<iostream>
using namespace std;
struct btree{
    char data;
    btree* leftchild;
    btree* rightchild;
    btree(){}
    btree(char c):data(c),leftchild(nullptr),rightchild(nullptr){}
};
btree* build(string preorder,string inorder){
    //创建
    if(preorder.size()==0){
        return nullptr;
    }
    char c=preorder[0];
    btree* root=new btree(c);
    int position=inorder.find(c);
    root->leftchild=build(preorder.substr(1,position), inorder.substr(0,position));
    root->rightchild=build(preorder.substr(position+1), inorder.substr(position+1));
    return root;
}
void postorder(btree* root){
    //后序遍历
    if(root==nullptr){
        return;
    }
    postorder(root->leftchild);
    postorder(root->rightchild);
    cout<<root->data;
}
int main(){
    string str1,str2;
    while(cin>>str1>>str2){
        btree* root=build(str1, str2);
        postorder(root);
        cout<<endl;
    }
    return 0;
}
全部评论

相关推荐

一只乌鸦:这不才9月吗,26到明年毕业前能一直找啊,能拿下提前批,转正的,offer打牌的都是有两把刷子的,为什么非要跟他们比。如果别人是9本硕+金牌+好几段大厂实习呢?如果别人是双非通天代呢?如果别人是速通哥呢?,做好自己就行了,我们做不到他们一样提前杀死比赛,但晚点到终点也没啥关系吧
双非应该如何逆袭?
点赞 评论 收藏
分享
头像
10-27 15:50
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务