c++

序列化二叉树

http://www.nowcoder.com/questionTerminal/cf7e25aa97c04cc1a68c8f040e71fb84

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:

    string SerializeCore(TreeNode *root) {
        if (root == NULL)  return "#!";
        return to_string(root->val)+"!"+ SerializeCore(root->left)+SerializeCore(root->right);        
    }

    char* Serialize(TreeNode *root) {    
        if (root == NULL) return NULL;
        string str = SerializeCore(root);
        return strdup(str.c_str());
    }

    TreeNode* DeserializeCore(stringstream& ss) {
        string str;
        getline(ss, str, '!');
        if (str == "#") return NULL;
        else {
            TreeNode* node = new TreeNode(stoi(str));
            node->left = DeserializeCore(ss);
            node->right = DeserializeCore(ss);
            return node;
        }
    }

    TreeNode* Deserialize(char *str) {
        if (str == NULL) return NULL;
        stringstream ss(str);
        return DeserializeCore(ss);
    }
};
全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务