0
点赞
收藏
分享

微信扫一扫

4道经典二叉树相关题目-二叉查找树的编码与解码

霸姨 2022-07-27 阅读 55


4道经典二叉树相关题目-二叉查找树的编码与解码_leetcode


4道经典二叉树相关题目-二叉查找树的编码与解码_leetcode_02


4道经典二叉树相关题目-二叉查找树的编码与解码_leetcode_03


4道经典二叉树相关题目-二叉查找树的编码与解码_leetcode_04


4道经典二叉树相关题目-二叉查找树的编码与解码_搜索_05


4道经典二叉树相关题目-二叉查找树的编码与解码_leetcode_06

//宽度搜索

class Codec {
public:

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "";
ostringstream os;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode *t = q.front(); q.pop();
if (t) {
os << t->val << " ";
q.push(t->left);
q.push(t->right);
} else {
os << "# ";
}
}
return os.str();

}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) return NULL;
istringstream is(data);
queue<TreeNode*> q;
string val = "";
is >> val;
TreeNode *res = new TreeNode(stoi(val)), *cur = res;
q.push(cur);
while (!q.empty()) {
TreeNode *t = q.front(); q.pop();
if (!(is >> val)) break;
if (val != "#") {
cur = new TreeNode(stoi(val));
q.push(cur);
t->left = cur;
}
if (!(is >> val)) break;
if (val != "#") {
cur = new TreeNode(stoi(val));
q.push(cur);
t->right = cur;
}
}
return res;
}
};


举报

相关推荐

0 条评论