题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

//指针用法、new用法   int *a=new int;  *a=1;
 
#include <iostream>
using namespace std;

struct TreeNode{
    char data;
    TreeNode* leftchild;
    TreeNode* rightchild;
    TreeNode(char c): data(c), leftchild(NULL), rightchild(NULL){}
} ;

TreeNode* Build(int& position,string str)
{
    char c=str[position++];
    if(c=='#')return NULL;

    TreeNode* root=new TreeNode(c);
    root->leftchild=Build(position,str);
    root->rightchild=Build(position,str);
    
    return root; 
}

void InOrder(TreeNode* root)
{
    if(root==NULL)return ;
    InOrder(root->leftchild);
    cout<<root->data<<" ";
    InOrder(root->rightchild);
}

int main() {
    string str;
    while (cin >>str) { 
        int position=0;
        TreeNode* root=Build(position,str);
        InOrder(root);
        cout<<endl;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-16 14:00
机械打工仔:来挂自己了,经典巨婴从校园投入职场
点赞 评论 收藏
分享
07-01 13:37
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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