剑指 Offer 37. 序列化二叉树(困难题)

题目描述:
请实现两个函数,分别用来序列化和反序列化二叉树。

示例:

你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

序列化为 “[1,2,3,null,null,4,5]”

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null){
            return "[]";
        }
        StringBuilder sb = new StringBuilder("[");
        Queue<TreeNode> que = new LinkedList<>();
        que.add(root);
        while (!que.isEmpty()){
            int times = que.size();
            while (times-- > 0){
                TreeNode p = que.poll();
                if(p == null){
                    sb.append("null");
                }else {
                    sb.append(p.val);
                    que.add(p.left);
                    que.add(p.right);
                }
                sb.append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("[]")){
            return null;
        }
        String[] sp = data.substring(1,data.length()-1).split(",");
        int i = 1;
        Queue<TreeNode> que = new LinkedList<>();
        TreeNode root = new TreeNode(Integer.valueOf(sp[0]));
        que.add(root);
        while (i < sp.length){
            TreeNode p = que.poll();
            if(!sp[i].equals("null")){
                p.left = new TreeNode(Integer.valueOf(sp[i]));
                que.add(p.left);
            }else {
                p.left = null;
            }
            i++;
            if(!sp[i].equals("null")){
                p.right = new TreeNode(Integer.valueOf(sp[i]));
                que.add(p.right);
            }else {
                p.right = null;
            }
            i++;
        }
        return root;
    }
}

你可能感兴趣的:(leetcode刷题整理)