题解 | #二维数组中的查找#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
层序遍历Java实现
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.LinkedList;
public class Solution {
String Serialize(TreeNode root) {
if(root == null)
return null;
LinkedList<TreeNode> queue = new LinkedList();
queue.add(root);
String res = "{";
boolean flag = true;
while(flag){
flag = false;
int size = queue.size();
for(int i=0; i<size; i++){
TreeNode node = queue.poll();
if(node == null){
if(i != size-1 || flag == true)
res = res + "#,";
}else{
res = res + node.val + ",";
queue.add(node.left);
queue.add(node.right);
if(node.left != null || node.right != null)
flag = true;
}
}
}
return res.substring(0,res.length()-1).concat("}");
}
TreeNode Deserialize(String str) {
System.out.println(str);
if(str == null || "".equals(str))
return null;
String[] strs = str.replace("{","").replace("}","").split(",");
LinkedList<TreeNode> queue = new LinkedList();
TreeNode head = new TreeNode(Integer.parseInt(strs[0]));
queue.add(head);
TreeNode node = null;
int i = 1;
while(i < strs.length){
if(!queue.isEmpty())
node = queue.poll();
if(!"#".equals(strs[i++])){
TreeNode newNode = new TreeNode(Integer.parseInt(strs[i-1]));
node.left = newNode;
queue.add(node.left);
}
if(i < strs.length && !"#".equals(strs[i++])){
TreeNode newNode = new TreeNode(Integer.parseInt(strs[i-1]));
node.right = newNode;
queue.add(node.right);
}
}
return head;
}
}