I think the key to reduce time is to use string builder I got TLE use string even O(n)


  • 0
    W
    below is my ac answer
        public String serialize(TreeNode root) {
        String ser = new String();
        StringBuilder sb = new StringBuilder();
        if (root == null) {
            return ser;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            if (temp != null) {
                queue.offer(temp.left);
                queue.offer(temp.right);
                sb.append(ser).append(temp.val).append(",");
            } else {
                sb.append("#").append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        String[] array = data.split(",");
        int val = Integer.parseInt(array[0]);
        TreeNode node = new TreeNode(val);
        queue.offer(node);
        int index = 1;
        while (!queue.isEmpty()) {
            TreeNode n = queue.poll();
            
            if (index < array.length && !array[index].equals("#")) {
                int value = Integer.parseInt(array[index]);
                TreeNode ns = new TreeNode(value);
                n.left = ns;
                queue.offer(ns);
            }
            index++;
            if (index < array.length && !array[index].equals("#")) {
                int value = Integer.parseInt(array[index]);
                TreeNode ns = new TreeNode(value);
                n.right = ns;
                queue.offer(ns);
            }
            index++;
        }
        return node;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.