LeetCode之Serialize and Deseriali

2019-08-14  本文已影响0人  糕冷羊

问题:



方法:
序列化与反序列化均通过递归实现,序列化时每一个子树用()包裹,层层包裹,最后输出1(2(3)(4))()形式的序列;反序列化时逻辑相反,通过()层层进入,从最底层开始还原节点,最后递归返回到上层,设置左子树和右子树,最后递归到根节点输出即为原树。

具体实现:

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null)
            return "";
        if (root.left == null && root.right == null)
            return root.val + "";
        else if (root.left == null)
            return root.val + "()" + "(" + serialize(root.right) + ")";
        else if (root.right == null)
            return root.val + "(" + serialize(root.left) + ")";
        return root.val + "(" + serialize(root.left) + ")" + "(" + serialize(root.right) + ")";
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String s) {
        if (s == null || s.length() == 0) return null;

        int firstParen = s.indexOf("(");
        int val = firstParen == -1 ?  Integer.parseInt(s) : Integer.parseInt(s.substring(0, firstParen));
        TreeNode cur = new TreeNode(val);

        if (firstParen == -1) return cur;

        int start = firstParen, leftParenCount = 0;
        for (int i = start; i < s.length(); i++) {
            if (s.charAt(i) == '(') leftParenCount++;
            else if (s.charAt(i) == ')') leftParenCount--;

            if (leftParenCount == 0 && start == firstParen)  {
                cur.left = deserialize(s.substring(start + 1, i));
                start = i + 1;
            } else if (leftParenCount == 0) {
                cur.right = deserialize(s.substring(start + 1, i));
            }
        }
        return cur;
    }

    public static void main(String args[]) {

    }

有问题随时沟通

具体代码实现可以参考Github

上一篇下一篇

猜你喜欢

热点阅读