leetcode--树的序列化与反序列化

序列化:利用队列,先将根节点放在队列中,然后从队列中poll节点出来在把左子节点和右子节点放入队列中。循环至队列为空。

反序列化:也是使用队列

public TreeNode Unserialize(String s){
        if(s==null)return null;
        if(s.length()==0)return null;
        s=s.substring(1,s.length()-1);
        String[]nums=s.split(",");
        Queuequeue=new LinkedList();
        TreeNode root=null;
        boolean isLeft=true;
        for(String num:nums){
            TreeNode current=null;
            if(num.equals("#"))current=null;
            else current=new TreeNode(Integer.parseInt(num));
            if(root==null){
                root=current;
                queue.add(root);
                continue;
            }
            TreeNode last=queue.peek();
            if(isLeft){
                last.left=current;
                if(current!=null)queue.add(current);
                isLeft=false;
                continue;
            }else{
                last.right=current;
                queue.poll();
                if(current!=null)queue.add(current);
                isLeft=true;
            }
        }
        return root;
    }
    public String Serialize(TreeNode root){
        if(root==null)return "";
        StringBuilder sb=new StringBuilder();
        sb.append(root.val);
        sb.append(',');
        Queuequeue=new LinkedList();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode current=queue.poll();
            TreeNode left=current.left;
            TreeNode right=current.right;
            if(left==null&&right==null&&queue.isEmpty())break;
            if(left!=null){
                sb.append(left.val);
                sb.append(',');
                queue.add(left);
            }else{
                sb.append("#,");
            }
            if(right!=null){
                sb.append(right.val);
                sb.append(',');
                queue.add(right);
            } else{
                sb.append("#,");
            }
        }
        return sb.substring(0,sb.length()-1);
    }


 
  
 
  

你可能感兴趣的:(leetcode)