一、题目
分析:
用一定方式记录二叉树成字符串,然后再将字符串解析成二叉树
无所谓遍历顺序,先序、中序、后续都可以,甚至按层遍历也是可以的,只要前后规则一致就是可以的
然后我是采用左神的方法,节点之间使用_占位符,空指针用#表示,否则不是很难知道左右子树什么时候终止,左神机智
一个小例子
比如这个,按照先序遍历序列化结果为:0_1_3_#_#_#_2_#_4_#_#
然后反序列化的时候,根据占位符和表示空的符号就可以生成一棵二叉树
二、代码实现(java)
知识点:
看API:
add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw
IllegalStateException
or returnfalse
.offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return
false
.
区别:两者都是往队列尾部插入元素,不同的时候,当超出队列界限的时候,add()方法是抛出异常让你处理,而offer()方法是直接返回false
实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null){
return "#_";
}
String res = root.val + "_";
res += serialize(root.left);
res += serialize(root.right);
return res;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String []values = data.split("_");
Queue<String> queue = new LinkedList<String>();
for(int i = 0; i!=values.length; i++){
queue.offer(values[i]);
}
return reconPreOrder(queue);
}
public TreeNode reconPreOrder(Queue<String> queue){
String value = queue.poll();
if(value.equals("#")){
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(value));
root.left = reconPreOrder(queue);
root.right = reconPreOrder(queue);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));