序列化二叉树--细节需格外注意

查细节花了好久,,欲哭无泪

 

时间限制:1秒 空间限制:32768K 热度指数:137899

算法知识视频讲解

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

 

序列化: 

    //使用前序遍历序列化二叉树
    String Serialize(TreeNode root) {
        if(root==null)    return null;
        StringBuilder res= new StringBuilder();
        SerializeCore(root, res);
        return res.toString();
    }
    void SerializeCore(TreeNode root, StringBuilder res){
        if(root==null){
            res.append("#,");
            return; //细节1:如果该情况处理完就返回应该加return,并括在一起啊!!!
        }
        res.append(root.val+",");
        SerializeCore(root.left, res);
        SerializeCore(root.right, res);
    }

反序列化 

    //反序列化:根据某种遍历方式得到的序列化字符串结果,重构二叉树
    TreeNode Deserialize(String str) {
        if(str==null)    return null;
        String[] str1= str.split(",");
        TreeNode root= null;
        root= DeserializeCore(str1, root);
        return root;
    }
    int index= -1;
    TreeNode DeserializeCore(String[] str1, TreeNode root){
        index++;
        if(index>=str1.length)    return null;
        if(!str1[index].equals("#")){//细节2:基本类型封装后或字符串不能用单纯的==来判断相等
            root= new TreeNode(Integer.valueOf(str1[index]));
            root.left= DeserializeCore(str1, root.left);
            root.right= DeserializeCore(str1, root.right);
        }
        return root;
    }

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值