【题目】
将一棵树转为字符串存在内存中,再将字符串转换还原成树
【扩展】
如何判断一棵树是不是另一棵树的子树
可以将这个问题转化为一个字符串是否是另一个字符串的子串
【思路】
二叉树的先序遍历
private String serialByPre(Node head){
if (null == head){
return "#_";
}
String str = head.value + "_";
str += serialByPre(head.left);
str += serialByPre(head.right);
return str;
}
private Node reconSerialByPre(String str){
if (StringUtils.isEmpty(str)){
return null;
}
str = str.replace("_",",");
String[] arr = str.split(",");
LinkedList<String> queue = new LinkedList<>();
for (String s : arr) {
queue.add(s);
}
return process(queue);
}
private Node process(LinkedList<String> queue){
String poll = queue.poll();
if (poll.equals("#")){
return null;
}
Node node = new Node(Integer.valueOf(poll));
node.left = process(queue);
node.right = process(queue);
return node;
}
测试代码
public class SerializeAndReconstructTree {
public static class Node{
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
}
}
private static String serialByPre(Node head){
if (null == head){
return "#_";
}
String str = head.value + "_";
str += serialByPre(head.left);
str += serialByPre(head.right);
return str;
}
private static Node reconSerialByPre(String str){
if (StringUtils.isEmpty(str)){
return null;
}
str = str.replace("_",",");
String[] arr = str.split(",");
LinkedList<String> queue = new LinkedList<>();
for (String s : arr) {
queue.add(s);
}
return process(queue);
}
private static Node process(LinkedList<String> queue) {
String poll = queue.poll();
if (poll.equals("#")){
return null;
}
Node node = new Node(Integer.valueOf(poll));
node.left = process(queue);
node.right = process(queue);
return node;
}
public static void main(String[] args) {
Node node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.right.left = new Node(6);
node.right.right = new Node(7);
node.left.left.left = new Node(8);
node.left.left.right = new Node(9);
String res = serialByPre(node);
System.out.println(res);
Node node1 = reconSerialByPre(res);
System.out.println();
Node node2 = new Node(4);
node2.left = new Node(8);
node2.right = new Node(10);
String res2 = serialByPre(node2);
System.out.println(res2);
//判断一棵树是否是另一棵的子树,可以利用序列化成字符串后进行判断
int i = res.indexOf(res2);
//返回值为>=0的数字,则是存在的,若返回值为-1,则是不存在的
System.out.println(i);
}
}