Lintcode7 二叉树的序列化和反序列化

public class Solution {
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    public String serialize(TreeNode root) {
        // write your code here
        if(root == null) return "{}";
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(root.val);
        while(!q.isEmpty()){
            TreeNode s = q.poll();
            if(s != null){
                q.add(s.left);
                if(s.left != null){
                    sb.append(",");
                    sb.append(s.left.val);
                }else{
                    sb.append(",#");
                }
                q.add(s.right);
                if(s.right != null){
                    sb.append(",");
                    sb.append(s.right.val);
                }else{
                    sb.append(",#");
                }
            }
        }
        sb.append("}");
        return sb.toString();
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
        // write your code here
        if (data.equals("{}")) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        TreeNode root = new TreeNode(Integer.valueOf(vals[0]));
        ArrayList<TreeNode> q = new ArrayList<>();
        q.add(root);
        int index = 0;
        boolean isLeft = true;
        for(int i = 1; i < vals.length; i++){
            if(!vals[i].equals("#")){
                int s = Integer.parseInt(vals[i]);
                TreeNode node = new TreeNode(s);
                if(isLeft){
                    q.get(index).left = node;
                }else{
                    q.get(index).right = node;
                }
                q.add(node);
            }
            if(!isLeft){
                index++;
            }
            isLeft = !isLeft;
        }
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值