297. Serialize and Deserialize Binary Tree
2016-02-10 17:29
344 查看
/** * 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 { private: void serialize_dfs(TreeNode *root, string &res, bool first) { if (!first) { res += ","; } if (!root) { res += "#"; return; } res += to_string(root->val); serialize_dfs(root->left, res, false); serialize_dfs(root->right, res, false); } void deserilize_dfs(TreeNode *&root, string &data) { size_t pos = data.find(","); if (pos == std::string::npos) return; string val = data.substr(0, pos); data = data.substr(pos + 1); if (val == "#") return; root = new TreeNode(stoi(val)); deserilize_dfs(root->left, data); deserilize_dfs(root->right, data); } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string data; serialize_dfs(root, data, true); return data; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.size() == 0) return NULL; TreeNode *root = NULL; deserilize_dfs(root, data); return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
相关文章推荐
- [HTTP]HTTP协议的状态码
- nyoj 1057
- 安卓开发——final的用法
- 非常好用的颜色吸取器PicPick
- The Java™ Tutorials — Concurrency :前言
- 编写应用程序消息
- Linux查看端口占用情况和开启端口命令
- Hadoop copyToLocalFile报空指针错误
- 哈理工oJ 1211 火车上的人数【暴力枚举】
- 挑战NPC
- 数组名和数组名取地址& 的区别
- C++错误 C3861“getline”: 找不到标识符
- 前端笔记十二,表格、列表相关属性及media query
- hdoj 2067小兔的棋盘
- 如何读取maven项目中的resources
- Asp.net MVC中的ViewData与ViewBag
- HDU 2191 悼念512汶川大地震遇难同胞――珍惜现在,感恩生活2191
- Android EditText取消焦点并关闭输入法
- jquery.extend 函数详解
- 【CSS笔记】display:inline-block的使用