C++二叉树序列化与反序列化

反序列化:输入为字符串,根据输入创建二叉树

序列化:输入为二叉树,输出为字符串

struct TreeNode//定义二叉树
{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() :left(nullptr), right(nullptr) {}
	TreeNode(int x) :val(x), left(nullptr), right(nullptr) {}
};

class Codec {
public:
	void preorder(TreeNode* root, string& res) {//先序遍历将二叉树序列化
		if (!root) {
			res += "null,";
			return;
		}
		res += to_string(root->val) + ",";
		preorder(root->left, res);
		preorder(root->right, res);
	}

	// Encodes a tree to a single string.
	string serialize(TreeNode* root) {
		string res;
		preorder(root, res);
		res.insert(res.begin(), '[');
		res[res.size() - 1] = ']';
		return res;
	}

	queue<string> split(string& data) {//将字符串分割为单个字符
		int start = 1;
		queue<string> res;
		std::string::size_type pos;
		while (1) {
			pos = data.find(',', start);
			if (pos == string::npos)break;
			res.push(data.substr(start, pos - start));
			start = pos + 1;
		}
		res.push(data.substr(start, 1));
		return res;
	}
	TreeNode* deserialize(queue<string>& str) {
		if (str.empty())return NULL;
		string first = str.front();
		str.pop();
		if (first == "null")return NULL;
		TreeNode* root = new TreeNode(stoi(first));//创建根节点
		queue<TreeNode*>q;
		q.push(root);
		TreeNode* bt;
		while (!q.empty()) {
			bt = q.front();
			q.pop();
			if (!bt)continue;
			if (!str.empty()) {//构造左孩子
				string first = str.front();
				str.pop();
				if (first == "null")bt->left = nullptr;
				else bt->left = new TreeNode(stoi(first));
				q.push(bt->left);
			}
			else {
				bt->left = nullptr;
			}
			if (!str.empty()) {//构造右孩子
				string first = str.front();
				str.pop();
				if (first == "null")bt->left = nullptr;
				else bt->right = new TreeNode(stoi(first));
				q.push(bt->right);
			}
			else {
				bt->right = nullptr;
			}
		}
		return root;
	}
	TreeNode* deserialize(string data) {
		queue<string>str;
		str = split(data);
		return deserialize(str);
	}
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一步倾川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值