LeetCode 297. Serialize and Deserialize Binary Tree

题目大意: 将二叉树序列化,返回序列化的String,和反序列化还原。

解题思路:
技巧在于将null记录为#便于将来判断。有两种解法。

  1. Level Order Traversal - BFS的思想将每一层记录下来,反序列化时也按照层级遍历的方法依次设置为上一个queue里面的元素的左孩子和右孩子。
  2. 更好的方法为preorder traversal,是可以handle变种题目的解法,利用preorder是root—>left->right的顺序,用一个deque来不断把头部的元素poll出,递归调用函数构建还原二叉树。
    //Solution 1: using Level order traversal
    public static String serialize(TreeNode root) {
        if (root == null ) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        while(!q.isEmpty()) {
            TreeNode curr = q.poll();
            if (curr == null) {
                sb.append("#,");
            } else {
                sb.append(curr.val + ",");
                q.offer(curr.left);
                q.offer(curr.right);
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     *      1
     *     / \
     *    2   3
     *   /   / \
     *  4   2   4
     *  /
     * 4
     * [1,2,3,4,#,2,4,4]
     * @param input
     * @return
     */

    public static TreeNode deSerialize(String input) {
        if (input == null || input.length() == 0) {
            return null;
        }
        String[] strs = input.split(",");
        TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);

        for(int i = 1; i < strs.length; i++){
            TreeNode curr = q.poll();
            if (curr == null) continue;
            if (!strs[i].equals("#")) {
                curr.left = new TreeNode(Integer.valueOf(strs[i]));
                q.offer(curr.left);
            }

            i++;

            if (i < strs.length && !strs[i].equals("#")) {
                curr.right = new TreeNode(Integer.valueOf(strs[i]));
                q.offer(curr.right);
            }

        }
        return root;

    }
    //Solution II: using 2 preorder traversal
    private static final String DELIMITER = ",";
    private static final String NN = "#";

    // Encodes a tree to a single string.
    public static String serialize2(TreeNode root) {
        //using preorder traversal
        StringBuilder res = new StringBuilder();
        serializeHelper(root, res);
        res.deleteCharAt(res.length() - 1);
        return res.toString();
    }
    private static void serializeHelper(TreeNode root, StringBuilder res) {
        if (root == null) {
            res.append(NN).append(DELIMITER);
            return;
        }
        res.append(root.val).append(DELIMITER);
        serializeHelper(root.left, res);
        serializeHelper(root.right, res);
    }

    // Decodes your encoded data to tree.
    public static TreeNode deserialize2(String data) {
        Deque<String> deque = new LinkedList<>();
        deque.addAll(Arrays.asList(data.split(DELIMITER)));
        return deserializeHelper(deque);
    }
    private static TreeNode deserializeHelper(Deque<String> deque) {
        String now = deque.pollFirst();
        if (now.equals(NN)) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(now));
        node.left = deserializeHelper(deque);
        node.right = deserializeHelper(deque);
        return node;
    }
    public static void main(String[] args) {
        //solution 1 level order
        TreeNode root1 = deSerialize("1,2,3,4,#,5,6,7");
        String result1 = serialize(root1);
        System.out.println(result1);

        //solution 2 preorder - 变种,可以要求输出一个LinkedList,而不是String
        TreeNode root2 = deserialize2("3,4,1,#,#,2,#,#,5,#,6,#,#");
        String result2 = serialize2(root2);

        System.out.println(result2);

    }

胡椒五菇
7 声望1 粉丝

保持学习