题解 | #二叉树遍历#

二叉树遍历

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;
    }
}

全部评论

相关推荐

01-16 18:34
四川大学 Java
欢迎加入AI:没有啥稳定不稳定,一切都源于业务快速发展还是收缩。我当年一开始去的央企,业务不赚钱,也贼卷,慢慢就开始优化了。。。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务