297. Serialize and Deserialize Binary Tree【力扣】

题意理解

对二叉树序列化和反序列化

问题分析

识别空树和空节点,对空树设置一个字符'#'

为了方便读取字符串,引入istringstream, 然后用cin>> istringstream, 逐个读节点值,再用stoi转化为节点整数值。

其他

链接

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
       if (root == NULL) return "#";
        return to_string(root->val) + ' ' + serialize(root -> left) + ' ' + serialize(root -> right);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
    
    TreeNode* deserialize(istringstream & in)
    {
        string val;
        in >> val;
        if (val == "#")
            return NULL;
        TreeNode* root = new TreeNode(stoi(val));
        root -> left = deserialize(in);
        root -> right = deserialize(in);
        return root;
    }

猜你喜欢

转载自blog.csdn.net/xiexie1357/article/details/88342882