C ++反序列化二叉树

我正在尝试序列化然后反序列化二叉树,但是在反序列化部分似乎遇到了障碍。我有以下代码:

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
    std::ostringstream oss;
    preorder_traversal(root,oss);
    return oss.str();
}

void preorder_traversal(TreeNode *root,ostringstream &oss) {
    if(root == nullptr) {
        oss << "null" << " "; // String streams are delimited by the space character
        return;
    }

    oss << root->val << " "; // String streams are delimited by the space character
    preorder_traversal(root->left,oss);
    preorder_traversal(root->right,oss);
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
    std::istringstream iss(data);
    TreeNode *root;
    deserialize_tree(root,iss);
    return root;
}

void deserialize_tree(TreeNode *root,istringstream &iss) {        
    string current_val;
    iss >> current_val;
    if(current_val == "null") return;

    root = new TreeNode(std::stoi(current_val)); 

    // Testing to see if root->val is being assigned the correct value
    std::cout << root->val << std::endl;

    deserialize_tree(root->left,iss);
    deserialize_tree(root->right,iss);
}; 

我面临的问题是,即使std::cout << root->val << std::endl表明在我最终{{1}时,在TreeNodes函数中值已分配给新创建的deserialize_tree() }在return root函数中,我得到一个空输出,这使我很头疼。

注意:如果有人想尝试在某些示例上运行上述代码,可以在https://leetcode.com/problems/serialize-and-deserialize-binary-tree/进行测试。

z156578453 回答:C ++反序列化二叉树

也许您需要传递指针并设置其指向的值? (还没有尝试过,但我想这是问题所在)

// note the **root
void deserialize_tree(TreeNode **root,istringstream &iss) {        
    string current_val;
    iss >> current_val;
    if(current_val == "null") return;

    // pass pointer in and set the value it pointed to
    *root = new TreeNode(std::stoi(current_val)); 

    // Testing to see if root->val is being assigned the correct value
    std::cout << (*root)->val << std::endl;

    // pass pointer
    deserialize_tree(&root->left,iss);
    deserialize_tree(&root->right,iss);
}; 

您必须修改原型,并且各处都需要调用此函数

,

在您提供的root = new TreeNode(std::stoi(current_val));的代码段中,正在更新root的本地实例,并且对调用函数没有任何影响。

以下希望对您有用,

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
    std::istringstream iss(data);
    TreeNode *root;
    deserialize_tree(root,iss);
    return root;
}

void deserialize_tree(TreeNode* &root,istringstream &iss) {        
    string current_val;
    iss >> current_val;
    if(current_val == "null") {root = nullptr;return;}

    root = new TreeNode(std::stoi(current_val)); 

     // Testing to see if root->val is being assigned the correct value
     std::cout << (root)->val << std::endl;
    deserialize_tree(root->left,iss);
    deserialize_tree(root->right,iss);
}
本文链接:https://www.f2er.com/2908937.html

大家都在问