树的序列化和反序列化

11 篇文章 0 订阅

树的序列化和反序列化

一颗普通树进行序列化和反序列化的算法

class Node {
    public int val;
    public List<Node> child;
    public Node(int val){
        this.val = val;
    }
    public Node(int val, List<Node> child){
        this.val = val;
        this.child = child;
    }
}

//把树序列化为字符串
public static String serialize(Node root){
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        String result = "[" + root.val + "]";
        while(!queue.isEmpty()){
            String tmpResult = ":";
            List<Node> nodes = new ArrayList<Node>();
            while(!queue.isEmpty()){
                nodes.add(queue.removeFirst());
            }
            String nodeStr;
            for(Node node:nodes){
                nodeStr = "";
                if(node.child != null){
                    for(Node n:node.child){
                        nodeStr += nodeStr.equals("")?n.val:"," + n.val;
                        queue.add(n);
                    }
                }
                tmpResult += "[" + nodeStr + "]";
            }
            if(!queue.isEmpty()){
                result += tmpResult;
            }            
        }
        return result;
    }

//把字符串反序列化为树
public static Node unserialize(String str){
        String[] splitStr = str.split(":");
        Node result = null;
        LinkedList<Node> queue = new LinkedList<>();
        for(String row:splitStr){
            String[] elems = row.split("]");
            for(String elem:elems){
                if(!elem.equals("[")){
                    String refElem = elem.replace("[", "");
                    String[] refElems = refElem.split(",");
                    ArrayList<Node> childs = new ArrayList<>();
                    for(String refEl:refElems){
                        Node node = new Node(Integer.valueOf(refEl));
                        childs.add(node);
                        queue.add(node);
                    }
                    if(result == null){
                        result = childs.get(0);
                        break;
                    }
                    
                    Node parentNode = queue.removeFirst();
                    parentNode.child = childs;
                }else{
                    queue.removeFirst();
                }
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值