面试题37

请实现两个函数,分别用来序列化和反序列化二叉树。

示例: 

你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

序列化为 "[1,2,3,null,null,4,5]"

Solutions

  1. preorder traversal with recursion

/**
 * 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:
    void serialize(TreeNode * root, string & s) {
        if (!root)
            s.push_back(',');
        else {
            s += to_string(root->val) + ",";
            serialize(root->left, s);
            serialize(root->right, s);
        }
    }

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        serialize(root, res);
        return res;
    }
    int deserialize(string & s, int start, TreeNode ** root) {
        if (s[start] == ',') {
            *root = nullptr;
            return start + 1;
        }
        else {
            int end = start;
            while (s[end] != ',') end++;
            TreeNode * cur = new TreeNode(stoi(s.substr(start, end - start)));
            *root = cur;
            end = deserialize(s, end + 1, &(cur->left));
            end = deserialize(s, end, &(cur->right));

            return end;
        }
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        TreeNode * root;
        deserialize(data, 0, &root);
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
  1. level order traversal with queue

Last updated

Was this helpful?