0
点赞
收藏
分享

微信扫一扫

LeetCode-树-前序遍历(DFS)-二叉树的序列化与反序列化

乱世小白 2022-01-31 阅读 46

1 题目

剑指 Offer II 048. 序列化与反序列化二叉树

297. 二叉树的序列化与反序列化

2 实现

// 此时使用的是 DFS
// 参考链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/
class Codec {
public:
	// Encodes a tree to a single string.
	string serialize(TreeNode* root) {
		if (!root)
            return "null";
        //使用前序遍历,是因为 根|左|右根∣左∣右 的打印顺序,在反序列化时更容易定位出根节点的值。
        string res(to_string(root->val));
        res.append(1,',').append(serialize(root->left));
        res.append(1,',').append(serialize(root->right));
		return res;
	}

	// Decodes your encoded data to tree.
	TreeNode* deserialize(string data) {
		if (data.empty())
			return NULL;

		size_t pos = -1, lastPos = 0;
		string str;
		queue<string> q;
		while ((pos = data.find(',', lastPos)) != string::npos)
		{
			str = data.substr(lastPos, pos - lastPos);
			lastPos = pos + 1;
			q.push(str);
		}

		str = data.substr(lastPos);
		if (!str.empty())
		{			
			q.push(str);
		}

        return buildTree(q);
	}

    TreeNode* buildTree(queue<string>& q)
    {
        string str = q.front();
        q.pop();
		if (str.compare("null") == 0)
			return NULL;

        TreeNode *root = new TreeNode(std::stoi(str));
        root->left = buildTree(q);
        root->right = buildTree(q);

        return root;
    }
};
举报

相关推荐

0 条评论