题解 | 二叉树遍历

二叉树遍历

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

#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
struct  treenode {
        char data;
        treenode* left;
        treenode* right;
        treenode(char c): data (c),left(NULL),right(NULL){}
    };
// get the pre-order to build the tree
    treenode * buildtree(string & s  ,int& index) {
        //isempty 
        if(index >=s.length()) return NULL;
        char c=s[index];
        index++;
        //if this node is empty  ,then it cant have the children  ,just return NULL 
        if (c == '#') return NULL;
        treenode *node =new treenode(c);
        node ->left=buildtree(s, index);
        node ->right=buildtree(s, index);
        return node;
    }
    // in-order 
    void inorder (treenode *t){
        if(t==NULL) return;
        inorder(t->left);
        cout << t->data <<" ";
        inorder(t->right);
    }
int main() {
    // get the input tree first 
    int index =0;
    string s ;
    cin >> s;
    treenode* t = buildtree(s, index);
    inorder(t);
    return 0;
}
// 64 位输出请用 printf("%lld")

思路很简单 只要把格式写对就能做出来

全部评论

相关推荐

04-08 23:37
已编辑
东华大学 结构工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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