【英雄算法六月集训】Day18

【英雄算法六月集训】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. 二叉树的序列化与反序列化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值