美文网首页
297. Serialize and Deserialize B

297. Serialize and Deserialize B

作者: 夜皇雪 | 来源:发表于2016-11-24 06:58 被阅读0次
    
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root==null) return "";
            Queue<TreeNode> queue=new LinkedList<>();
            StringBuilder res=new StringBuilder();
            queue.offer(root);
            while(!queue.isEmpty()){
                TreeNode cur=queue.poll();
                if(cur==null){
                    res.append("n ");
                    continue;
                }
                res.append(cur.val+" ");
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
            return res.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data=="") return null;
            Queue<TreeNode> queue=new LinkedList<>();
            String[] values=data.split(" ");
            TreeNode root=new TreeNode(Integer.parseInt(values[0]));
            queue.offer(root);
            for(int i=1;i<values.length;i++){
                TreeNode cur=queue.poll();
                if(!values[i].equals("n")){
                    TreeNode left=new TreeNode(Integer.parseInt(values[i]));
                    cur.left=left;
                    queue.offer(left);
                }
                if (!values[++i].equals("n")) {
                    TreeNode right = new TreeNode(Integer.parseInt(values[i]));
                    cur.right = right;
                    queue.add(right);
                }
            }
            return root;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:297. Serialize and Deserialize B

          本文链接:https://www.haomeiwen.com/subject/zvhbpttx.html