题解 | #二叉树序列化与反序列化#
序列化二叉树
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;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root == null) {
return "#_" ;
}
return root.val + "_" + Serialize(root.left) + Serialize(root.right) ;
}
int index = 0 ;
TreeNode Deserialize(String str) {
if(index >= str.length()) {//索引超过直接返回null
return null ;
}
if(str.charAt(index) == '#') {
index+=2 ;//讲索引位置移动到下一个有效字符
return null ;
}
int i = index ;//寻找完整的数
while(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
i++ ;
}
TreeNode root = new TreeNode(Integer.parseInt(str.substring(index,i))) ;//构造完整数的节点
index = i+1 ;//讲索引位置移动到下一个有效字符
root.left = Deserialize(str) ;//递归
root.right = Deserialize(str) ;
return root ;
}
}
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录
传音控股公司福利 316人发布