Leetcode刷题 297. 449.二叉树 搜索二叉树的序列化与反序列-层序遍历

Leetcode刷题 297. 449.二叉树 搜索二叉树的序列化与反序列-层序遍历_第1张图片

Leetcode刷题 297. 449.二叉树 搜索二叉树的序列化与反序列-层序遍历_第2张图片

   void test(){
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left=treeNode2;
        treeNode1.right = treeNode3;
        treeNode3.right =treeNode5;
        treeNode3.left =treeNode4;
        String serialize = serialize(null);
        System.out.println("cccccccc"+serialize);
        TreeNode deserialize = deserialize(serialize);
        System.out.println("cccccccc"+serialize);
    }


    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        Queue queue = new LinkedList<>();
        if(root==null){
            stringBuilder.append("null");
        }else {
            queue.offer(root);
            stringBuilder.append(root.val);
        }

        while (!queue.isEmpty()){
            TreeNode poll = queue.poll();
            if(poll.left ==null){
                stringBuilder.append(",").append("null");
            }else {
                queue.offer(poll.left);
                stringBuilder.append(",").append(poll.left.val);
            }

            if(poll.right ==null){
                stringBuilder.append(",").append("null");
            }else {
                queue.offer(poll.right);
                stringBuilder.append(",").append(poll.right.val);
            }
        }

        stringBuilder.append("]");
        return stringBuilder.toString();


    }



    public TreeNode deserialize(String data) {

        String[] split = data.substring(1, data.length() - 1).split(",");
        Queue queue = new LinkedList<>();
        if(split.length==0||split[0].equals("null")){
            return null;
        }
        TreeNode root= new TreeNode(Integer.valueOf(split[0]));
        queue.add(root);
        for (int i = 0; i 

你可能感兴趣的:(算法)