剑指offer-序列化二叉树

60.序列化二叉树

题目内容:

代码及思路:

其中#表示的是nullptr,因此根据这个特点,反序列化为二叉树时,也是根据先根节点,后左右子树的顺序。

#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
};
class Solution {
public:
	void buildTree(TreeNode** root)
	{
		int temp;
		cin >> temp;
		if (temp == 0)
		{
			(*root)->val = 0;
			(*root) = nullptr;
			return;
		}
		else
		{
			(*root)->val = temp;
			(*root)->left = new TreeNode();
			buildTree(&(*root)->left);
			(*root)->right = new TreeNode();
			buildTree(&(*root)->right);
		}
	}
	char* Serialize(TreeNode* root)  //前序遍历从根节点开始,然后依次是左子树与右子树
	{
		if (!root)
			return "#,";
		string str = to_string(root->val);
		str.push_back(',');
		char* left = Serialize(root->left);
		char* right = Serialize(root->right);
		char* res = new char[strlen(left) + strlen(right) + str.size()];
		strcpy(res, str.c_str());  //从根节点开始复制
		strcat(res, left);
		strcat(res, right);
		return res;
	}
	TreeNode* Deserialize(char* str)
	{
		return deserialize(str);
	}
	TreeNode* deserialize(char* &str)
	{
		if (*str == '#')
		{
			str++;
			return nullptr;
		}
		int num = 0;
		while (*str != '\0'&&*str != ',')
		{
			num = num * 10 + (*(str++) - '0'); //将字符变为数字
		}
		TreeNode* pNode = new TreeNode();
		pNode->val = num;
		if (*str == '\0')     //临界值要处理好
			return pNode;
		else
		{
			++str;
		}
		pNode->left = deserialize(str);
		pNode->right = deserialize(str);
		return pNode;
			
	}
};
void main()
{
	Solution* object = new Solution();
	TreeNode* pNode = new TreeNode();
	object->buildTree(&pNode);
	char* str = object->Serialize(pNode);
	int len = strlen(str);
	str[len - 1] = '\0';
	TreeNode* depNode = new TreeNode();
	depNode = object->Deserialize(str);
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值