二叉树遍历

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=40&&tqId=21342&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

#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(int& pos,string str){
    char c=str[pos++];            //当前字符位置
    if(c=='#')                    //返回空树
        return NULL;
    TreeNode* root=new TreeNode(c);
    root->lchild=Build(pos,str);
    root->rchild=Build(pos,str);
    return root;
}

void InOrder(TreeNode* root){            //中序遍历
    if(root==NULL)
        return;
    InOrder(root->lchild);
    printf("%c ",root->data);
    InOrder(root->rchild);
    return;
}

int main(){
    string str;
    while(cin>>str){
        int pos=0;
        TreeNode* root=Build(pos,str);
        InOrder(root);
        printf("\n");
    }
    return 0;
}
全部评论

相关推荐

醉蟀:你不干有的是人干
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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