序列化二叉树
题目
请实现两个函数,分别用来序列化和反序列化二叉树。
思路:
-
序列化(题目要求按照层序遍历的顺序序列化,与剑指有所不同):
(1)按照层次遍历的套路,设置辅助队列
(2)空节点也要加入序列,所以每出队一个节点,判断是否为空
– 空则加入“null”
– 不空将其值加入序列中,然后左右子树入队(不管左右子树是否为空) -
反序列化
(1)python:利用队列按层构建二叉树,每构建一个节点的左右子节点,指针向右移动1位。
(2)C++:用一个vector辅助实现,先把序列存入vector,然后从根节点开始建树。每次i移动一个单位,j向右移动两次。
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* tmp = q.front();
q.pop();
if (tmp) {
out<<tmp->val<<" ";
q.push(tmp->left);
q.push(tmp->right);
} else {
out<<"null ";
}
}
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream input(data);
string val;
vector<TreeNode*> vec;
while(input >> val)
{
if(val=="null")
{
vec.push_back(NULL);
}
else
{
vec.push_back(new TreeNode(stoi(val)));
}
}
int j=1;
for(int i=0; j<vec.size(); ++i)
{
//i一次走一步,j一次走两步
if(vec[i]==NULL)
continue;
// 只要j没有到尾部
if(j < vec.size())
vec[i]->left = vec[j++];
if(j < vec.size())
vec[i]->right = vec[j++];
}
return vec[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return "[]"
queue = []
queue.append(root)
res = []
while queue:
temp = queue[0]
queue.pop(0)
if temp:
res.append(str(temp.val))
queue.append(temp.left)
queue.append(temp.right)
else:
res.append("null")
return '[' + ','.join(res) +']'
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == "[]":
return None
vals = data[1:-1].split(',')
i = 1
root = TreeNode(int(vals[0]))
queue = []
queue.append(root)
while queue: # 和C++中的for循环原理一样
temp = queue[0]
queue.pop(0)
if vals[i] != "null":
temp.left = TreeNode(int(vals[i]))
queue.append(temp.left)
i += 1
if vals[i] != "null":
temp.right = TreeNode(int(vals[i]))
queue.append(temp.right)
i += 1
return root