【英雄算法六月集训】Day18
331. 验证二叉树的前序序列化
Ⅰ 二叉树合不合法 可以判断每个节点的出入度
特征:
二叉树
class Solution {
public boolean isValidSerialization(String preorder) {
int in=-1;
int out=0;
for(int i=0;i<preorder.length();++i){
char c=preorder.charAt(i);
if(c == ','){
continue;
}
++in;
if(out<in){
return false;
}
if(c>='0'&&c<='9'){
out+=2;
while(i<preorder.length()&&preorder.charAt(i) !=',') ++i;
--i;
}
}
return in==out;
}
}
297. 二叉树的序列化与反序列化
特征:
递归
树的序列化
深度优先遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
public String dfs(TreeNode root){
if(root==null){
return "";
}
String l="",r="";
String valRet = root.val+"";
l="("+dfs(root.left)+")";
r="("+dfs(root.right)+")";
//a[s](l)(r)
String finalS = valRet+"["+l.length()+"]"+l+r;
System.out.println(finalS);//1[10](2[2]()())(3[10](4[2]()())(5[2]()()))
return finalS;
}
public TreeNode ndfs(String data,int l,int r){
int i;
int rootFlag=1;
int rootVal=0;
int placement=0;
if(l>r) return null;
for(i=l;i<data.length()&&data.charAt(i)!='[';++i){
if(data.charAt(i) == '-'){
rootFlag = -1;
}else{
rootVal = rootVal * 10+(data.charAt(i)-'0');
}
}
rootVal *=rootFlag;
TreeNode root = new TreeNode(rootVal);
for(i = i+1;i<data.length()&&data.charAt(i) !=']';++i){
placement = placement*10+(data.charAt(i)-'0');
}
root.left = ndfs(data,i+2,i+placement-1);
root.right = ndfs(data,i+2+placement,r-1);
return root;
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
String ret = "";
ret = dfs(root);
return ret;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
int len = data.length();
return ndfs(data,0,len-1);
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
剑指 Offer 37. 序列化二叉树
剑指 Offer II 048. 序列化与反序列化二叉树
代码同上 297. 二叉树的序列化与反序列化