【剑指37】序列化二叉树

方法一:dfs:时间O(n),空间O(n)

题解:

  • 序列化:
    • 规定序列化的格式:一个数据之后跟上逗号,如果空树则用 # 代替占位
    • 先序遍历二叉树,如果是空树则插入 #,如果不空则将数据转换成string类型并插入,最后添加逗号
  • 反序列化
    • 根据序列化的格式进行反序列化,如果当前字符是# 则赋空
    • 如果不是# ,则动态创建节点

时间:O(n) 遍历二叉树的所有节点,遍历 string 的所有元素都是O(n)
空间:O(n) 最坏情况二叉树是单支树,需要O(n)的递归空间

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
    
    
public:
    string ans;
    void dfs(TreeNode* root)
    {
    
    
        if (root == nullptr)
        {
    
    
            ans.push_back('#');
            return;
        }
        ans.append(to_string(root->val));
        ans.push_back(',');
        dfs(root->left);
        dfs(root->right);
    }
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) 
    {
    
    
        dfs(root);
        return ans;
    }
    int index = 0;
    TreeNode* Decodes(string& data)
    {
    
    
        TreeNode* root = nullptr;
        if (data[index] == '#')
        {
    
    
            index++;
            return root;
        }
        int pos = index;
        while (data[pos] != ',')
            pos++;
        int val = stoi(data.substr(index, pos - index));
        root = new TreeNode(val);
        index = pos + 1;
        root->left = Decodes(data);
        root->right = Decodes(data);
        return root;
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) 
    {
    
    
        TreeNode* root = Decodes(data);
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/114667655