lintcode binary-tree-serialization 二叉树的序列化与反序列化
2016-07-21 09:26
435 查看
问题描述
lintcode参考
Serialization/Deserialization of a Binary TreeLintCode Binary Tree Serialization
笔记
可以用先序遍历和
使用"#"来表示NULL的方法来序列化,最后也用先序遍历来反序列化。
代码
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { // write your code here string s = ""; writeTree(s, root); return s; } void writeTree(string &s, TreeNode* root) { if (root == NULL) { s += "# "; return; } s += (to_string(root->val) + ' '); writeTree(s, root->left); writeTree(s, root->right); } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { // write your code here int pos = 0; return readTree(data, pos); } TreeNode* readTree(string data, int& pos) { if (data[pos] == '#') { pos += 2; return NULL; } int nownum = 0; while (data[pos] != ' ') { nownum = nownum * 10 + (data[pos] - '0'); pos++; } pos++; TreeNode* nowNode = new TreeNode(nownum); nowNode->left = readTree(data, pos); nowNode->right = readTree(data, pos); return nowNode; } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C语言 二叉树的链式存储实例
- C++实现查找二叉树中和为某一值的所有路径的示例
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)