题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
} / import java.util.;
public class Solution {
//一个简单的BFS广度优先遍历
String Serialize(TreeNode root) {
if(root == null){
return "";
}
int depth = getDepth(root);
int size = (int)Math.pow(2,depth) * 2 - 3;
String str = "";
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(root);
while(!que.isEmpty()){
TreeNode tmpNode = que.poll();
if(tmpNode != null){
str += tmpNode.val;
}else{
str += '#';
}
str += " ";
if(tmpNode != null){
que.offer(tmpNode.left);
que.offer(tmpNode.right);
}
}
return str;
}
public static int getDepth(TreeNode root){
if(root == null){
return 0;
}
return Math.max(getDepth(root.left),getDepth(root.right)) + 1;
}
TreeNode Deserialize(String str) {
if(str.equals("")){return null;}
//分割成数组形式
String[] s1 = str.split(" ");
int len = s1.length;//数组长度
//逆过程
Queue<TreeNode> que1 = new LinkedList<TreeNode>();
//头节点
TreeNode root = new TreeNode(Integer.parseInt(s1[0]));
que1.offer(root);
for(int i = 1; i < s1.length - 1; i += 2){
//注意:两个数一组,因为要给倒出节点的左右节点分别赋值
TreeNode tmpNode = que1.poll();
//s1[i]非“#”,则s1[i]给左节点赋值,否则左节点为null
if(!s1[i].equals("#")){
int l = Integer.parseInt(s1[i]);
tmpNode.left = new TreeNode(l);
que1.offer(tmpNode.left);
}
//同上
if(!s1[i + 1].equals("#")){
int r = Integer.parseInt(s1[i + 1]);
tmpNode.right = new TreeNode(r);
que1.offer(tmpNode.right);
}
}
return root;
}
}