LeetCode 五月打卡-day11

Posted 王六六的IT日常

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 五月打卡-day11相关的知识,希望对你有一定的参考价值。

449. 序列化和反序列化二叉搜索树

参考题解:
【宫水三叶】前序遍历与 BST 特性(含二分优化)

public class Codec 
    public String serialize(TreeNode root) 
        if (root == null) return null;
        List<String> list = new ArrayList<>();
        dfs1(root, list);
        int n = list.size();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) 
            sb.append(list.get(i));
            if (i != n - 1) sb.append(",");
        
        return sb.toString();
    
    void dfs1(TreeNode root, List<String> list) 
        if (root == null) return ;
        list.add(String.valueOf(root.val));
        dfs1(root.left, list);
        dfs1(root.right, list);
    
    public TreeNode deserialize(String s) 
        if (s == null) return null;
        String[] ss = s.split(",");
        return dfs2(0, ss.length - 1, ss);
    
    TreeNode dfs2(int l, int r, String[] ss) 
        if (l > r) return null;
        int j = l + 1, t = Integer.parseInt(ss[l]);
        TreeNode ans = new TreeNode(t);
        while (j <= r && Integer.parseInt(ss[j]) <= t) j++;
        ans.left = dfs2(l + 1, j - 1, ss);
        ans.right = dfs2(j, r, ss);
        return ans;
    

以上是关于LeetCode 五月打卡-day11的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 五月打卡-day19

LeetCode 五月打卡-day07

LeetCode 五月打卡-day20

LeetCode 五月打卡-day08

LeetCode 五月打卡-day13

LeetCode 五月打卡-day06