lintcode 7. 二叉树的序列化和反序列化

描述
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

对二进制树进行反序列化或序列化的方式没有限制,LintCode 将您的 serialize 输出作为 deserialize 的输入,它不会检查序列化的结果。

思路:按树的深度依次存储,#表示子节点都是空的节点,$表示空节点。

class TreeNode {
public:
	int val;
	TreeNode *left, *right;
	TreeNode(int val) {
		this->val = val;
		this->left = this->right = NULL;
	}
};

class lintcode_7 {
public:
	void splitString(const string &s, vector<string> &v, string c)
	{
		string::size_type pos1, pos2;
		pos2 = s.find(c);
		pos1 = 0;
		while (string::npos != pos2)
		{
			v.push_back(s.substr(pos1, pos2 - pos1));
			pos1 = pos2 + c.size();
			pos2 = s.find(c, pos1);
		}
		if (pos1 != s.length())
			v.push_back(s.substr(pos1));
	}
	
	string serialize(TreeNode * root) {
		if (root == NULL) return "";
		vector<TreeNode *> vctNote;
		string strOut;
		vctNote.push_back(root);
		do
		{
			vector<TreeNode *> vctTemp;
			for (size_t i = 0; i < vctNote.size(); ++i)
			{
				if (vctNote[i] != 0)
				{
					strOut += to_string(vctNote[i]->val) + ",";
					if (vctNote[i]->left == NULL && vctNote[i]->right == NULL)
						strOut += "#,";
					else
					{
						vctTemp.push_back(vctNote[i]->left);
						vctTemp.push_back(vctNote[i]->right);
					}
				}
				else
					strOut += "$,";
			}
			vctNote = vctTemp;
		} while (vctNote.size() > 0);
		return strOut;
	}

	TreeNode * deserialize(string &data) {
		vector<string> vctSplit;
		splitString(data, vctSplit, ",");
		if (vctSplit.empty())
			return NULL;
		TreeNode * pHead = new TreeNode(stoi(vctSplit[0], nullptr, 0));
		vector<TreeNode *> vctNote;
		vctNote.push_back(pHead);
		size_t i = 1;
		while (i < vctSplit.size())
		{
			vector<TreeNode *> vctTemp;
			for (size_t n = 0; n < vctNote.size(); ++n)
			{
				if (i < vctSplit.size() && vctSplit[i] != "$")
				{
					TreeNode * pTemp = new TreeNode(stoi(vctSplit[i], nullptr, 0));
					vctNote[n]->left = pTemp;
					if (i + 1 < vctSplit.size())
					{
						if (vctSplit[i + 1] == "#")
							++i;
						else
							vctTemp.push_back(pTemp);
					}
				}
				if (i + 1 < vctSplit.size() && vctSplit[i + 1] != "$")
				{
					TreeNode * pTemp = new TreeNode(stoi(vctSplit[i + 1], nullptr, 0));
					vctNote[n]->right = pTemp;
					if (i + 2 < vctSplit.size())
					{
						if (vctSplit[i + 2] == "#")
							++i;
						else
							vctTemp.push_back(pTemp);
					}
				}
				i += 2;
			}
			vctNote = vctTemp;
		}
		return pHead;
	}
};
上一篇:HDU 3533 Escape(大逃亡)


下一篇:HDOJ-1002 A + B Problem II (非负大整数相加)