AcWing 50. 序列化二叉树,判断正负数【Java】
原题链接
困难
作者:
NayelyA
,
2020-04-13 01:09:33
,
所有人可见
,
阅读 913
Java 代码
/**
* 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 str=root.val+",";
str+=serialize(root.left);
str+=serialize(root.right);
return str;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
int u[]={0};
return dfsDeser(data,u);
}
TreeNode dfsDeser(String data,int u[]){
if(u[0]==data.length()) return null;
int k=u[0];
while(data.charAt(k)!=',') k++;
if(data.charAt(u[0])=='#'){
//跳过#和,
u[0]+=2;
return null;
}
int t=0;
//判断负数
boolean is_minus=false;
if(data.charAt(u[0])=='-') {
is_minus=true;
u[0]++;
}
//计算val值
for(int i=u[0];i<k;i++){
t=t*10+data.charAt(i)-'0';
}
if(is_minus)
t=-t;
//跳过逗号
u[0]=k+1;
TreeNode root=new TreeNode(t);
root.left=dfsDeser(data,u);
root.right=dfsDeser(data,u);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));