297. Serialize and Deserialize Binary Tree

本文介绍了一种使用广度优先搜索方法来序列化和反序列化二叉树的方法。序列化将二叉树转换为字符串,而反序列化则将字符串还原为原来的二叉树结构。该方法利用队列来处理节点,确保正确地遍历每一层。

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, 

or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. 

You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5
as  "[1,2,3,null,null,4,5]", just the same as  how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, 
so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


二叉树的序列化和反序列化。这里都用了广度优先的方式进行,用队列实现。实现没什么难点,注意空指针就行了。

这里遇到了坑,在序列化的时候,想着一个节点用完了,后面就没有用处了,反正后面返回的是字符串,所以每个节点的内存都释放掉了。

结果通过不了,内存出错了。可能测试的时候会出现一颗二叉树用几次的情况吧。


代码:

class Codec {
public:
	// Encodes a tree to a single string.
	string serialize(TreeNode* root) 
	{
		string res;
		if(!root) return "null";
		queue<TreeNode*>q;
		q.push(root);
		while(!q.empty())
		{
			TreeNode* tmp = q.front();
			q.pop();
			if(!tmp)	
			{
				res += "null,";
			}
			else
			{
				res += to_string(tmp->val) + ",";
				q.push(tmp->left);
				q.push(tmp->right);
			}
		}
		return res;
	}

	// Decodes your encoded data to tree.
	TreeNode* deserialize(string data) 
	{
		int pos = 0, n = data.size();
		data += ",";
		TreeNode* root = build_node(data, pos);
		if(!root) return NULL;
		queue<TreeNode*>q;
		q.push(root);
		while(!q.empty())
		{
			TreeNode* tmp = q.front();
			q.pop();
			if(pos >= n) break;
			tmp->left = build_node(data, pos);
			if(tmp->left) q.push(tmp->left);
			if(pos >= n) break;
			tmp->right = build_node(data, pos);
			if(tmp->right) q.push(tmp->right);
		}
		return root;
	}
private:
	TreeNode* build_node(const string& s, int& pos)
	{
		int end = s.find(",", pos);
		string tmp = s.substr(pos, end-pos);
		pos = end + 1;
		if(tmp == "null")
		{
			return NULL; 
		}
		else
		{
			TreeNode *node = new TreeNode(stoi(tmp));
			return node;
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值