LeetCode 449 Serialize and Deserialize BST (dfs 推荐)

244 篇文章 0 订阅
16 篇文章 0 订阅

Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Example 1:

Input: root = [2,1,3]
Output: [2,1,3]

Example 2:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • 0 <= Node.val <= 104
  • The input tree is guaranteed to be a binary search tree.

题目链接:https://leetcode.com/problems/serialize-and-deserialize-bst/

题目大意:设计一组序列化和反序列化二叉搜索树的算法

题目分析:其实做的过程中就发现我的做法根本没用到二叉搜索树的性质,是对于任何二叉树都适用的,思路:序列化直接用括号把左右子树包起来,反序列化先算出当前根的值,然后找第一个合法的括号序列,中间值即为左子树的序列化值,后面的括号序列中间值则为右子树序列化的值,递归计算即可

18ms,时间击败30%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "n";
        }
        if (root.left == null && root.right == null) {
            return root.val + "";
        }
        StringBuffer sb = new StringBuffer("");
        sb.append(root.val)
            .append("(").append(serialize(root.left)).append(")")
            .append("(").append(serialize(root.right)).append(")");
        return sb.toString();
    }

    public TreeNode _deserialize(String data, int l, int r) {
        //System.out.println(data);
        if (data.charAt(l) == 'n') {
            return null;
        }
        int val = 0, i = l;
        while (i < r && data.charAt(i) >= '0' && data.charAt(i) <= '9') {
            val = val * 10 + (data.charAt(i++) - '0');
        }
        TreeNode root = new TreeNode(val);
        if (i == r) {
            return root;
        }

        int top = 0;
        l = i;
        while (i < r) {
            if (data.charAt(i) == '(') {
                top++;
            } else if (data.charAt(i) == ')') {
                top--;
            }
            if (top == 0) {
                break;
            }
            i++;
        }
        // System.out.println("l = " + l + " i = " + i);
        root.left = _deserialize(data, l + 1, i);
        root.right = _deserialize(data, i + 2, r - 1);
        return root;
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        return _deserialize(data, 0, data.length());
    }
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;

比较好的做法是要利用二叉搜索树的性质,序列化取原树的后序遍历结果即可,反序列化思路:最右必为根,左边均小于根值的连续序列为左子树,均大于根值的连续序列为右子树,递归计算即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值