Encode integer to base36, to reduce string size. 11ms


  • 0
    Z
    import java.util.StringTokenizer;
    /**
     * preorder traversal + add nulls to serialization. 
     */ 
    
    public class Codec {
        // I know mutable state is not allowed. 
        final static String NULL = "." ;
        final static String SEPA = " ";
        final static int RADIX = Character.MAX_RADIX;
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            preOrder(root, sb);
            return sb.toString();
        }
    
        private void preOrder(TreeNode root, StringBuilder sb){
            if(root == null){
                sb.append(NULL).append(SEPA);
                return;
            }
    
            sb.append(Integer.toString(root.val, RADIX)).append(SEPA);
            preOrder(root.left, sb);
            preOrder(root.right, sb);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            StringTokenizer st = new StringTokenizer(data, SEPA);
            return build(st);
        }
    
        // no need to check for end of stream.
        // The parsing code will work if the tree structure is correctly serialized.
        private TreeNode build(StringTokenizer st){
            String tok = st.nextToken();
            if(tok.equals(NULL))
                return null;
    
            TreeNode root = new TreeNode(Integer.parseInt(tok,RADIX));
            root.left = build(st);
            root.right = build(st);
    
            return root;
        }
    }

Log in to reply
 

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