Java preorder with StringReader beat 99%


  • 2
    A
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder builder = new StringBuilder();
            serialize(root, builder);
            return builder.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            try {
                return deserialize(new java.io.StringReader(data));
            } catch (java.io.IOException e) {
                // should never happen ;)
                return null;
            }
        }
        
        public void serialize(TreeNode node, StringBuilder builder) {
            if (node == null) {
                builder.append(".,");
            } else {
                builder.append(node.val).append(",");
                serialize(node.left, builder);
                serialize(node.right, builder);
            }
        }
         
        public TreeNode deserialize(java.io.StringReader reader) throws java.io.IOException{
            String s = readNextFrom(reader);
            if (s.length() > 0) {
                TreeNode node = new TreeNode(Integer.valueOf(s));
                node.left = deserialize(reader);
                node.right = deserialize(reader);
                return node;
            } else {
                return null;
            }
        }
        
        private int c;
        private StringBuilder buffer = new StringBuilder();
        private String readNextFrom(java.io.StringReader reader) throws java.io.IOException {
            buffer.delete(0, buffer.length());
            while ((c=reader.read()) != ',' && c != -1) if (c != '.') buffer.append((char) c);
            return buffer.toString();
        }
    }

Log in to reply
 

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