1. 程式人生 > >[劍指offer] 61. 序列化二叉樹

[劍指offer] 61. 序列化二叉樹

int 二叉樹 pan ali 二叉 ear 默認 color back

題目描述

請實現兩個函數,分別用來序列化和反序列化二叉樹
題目很差,沒有測試樣例。 默認是先序遍歷序列化。
class Solution
{
  public:
    vector<int> vec;
    void Ser(TreeNode *pNode)
    {
        if (!pNode)
            vec.push_back(0x12345);
        else
        {
            vec.push_back(pNode->val);
            Ser(pNode->left);
            Ser(pNode
->right); } } TreeNode *Des(int *&p) { if (*p == 0x12345) { p++; return NULL; } TreeNode *res = new TreeNode(*p); p++; res->left = Des(p); res->right = Des(p); return res; }
char *Serialize(TreeNode *root) { vec.clear(); Ser(root); int *res = new int[vec.size()]; for (int i = 0; i < vec.size(); i++) res[i] = vec[i]; return (char *)res; } TreeNode *Deserialize(char *str) { int *p = (int *)str;
return Des(p); } };

[劍指offer] 61. 序列化二叉樹