题解 | 序列化二叉树

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
#include <string>
class Solution {
public:
    void dfs(TreeNode* root,string& str)
    {
        if(root == nullptr) 
        {
            str+="#,";
            return;
        }
        str += to_string(root->val)+",";
        dfs(root->left,str);
        dfs(root->right,str);
    }
    string str;
    char* Serialize(TreeNode *root) {    
        str.clear();
        dfs(root,str);
        cout<<str<<endl;
        return str.data();
    }
    TreeNode* redfs(string& str,int& idx)
    {
        if(idx>=str.size()) return nullptr;
        if(str[idx]=='#') 
        {
            idx++;
            return nullptr;
        }
        int sum = 0;
        for(;str[idx]!=',';idx++)
        {
            sum = sum * 10 + str[idx] - '0';
        }
        TreeNode* root = new TreeNode(sum);
        root->left = redfs(str, ++idx);
        root->right = redfs(str, ++idx);
        return root;
    }
    TreeNode* Deserialize(char *str) {
        string msg(str);
        int idx = 0;
        return redfs(msg,idx);
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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