Simple recursive solution, no queue, beat 99.46%


  • 0
    S
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Codec {
         void serialize(TreeNode root, StringBuilder builder) {
            if (root == null) {
                builder.append("null,");
                return;
            }
            
            builder.append(root.val);
            builder.append(",");
            serialize(root.left, builder);
            serialize(root.right, builder);
        }
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder builder = new StringBuilder();
            serialize(root, builder);
            return builder.toString();
        }
    
    
        public TreeNode deserialize(String data, int[] idx) {
            if (idx[0] > data.length() - 1) {
                throw new RuntimeException("wrong precondition");
            }
            int c = data.indexOf(',', idx[0]) ;
            String s = data.substring(idx[0], c);
            idx[0] = c + 1;
            
            if (s.equals("null")) {
                return null;
            }
            
            TreeNode node = new TreeNode(Integer.parseInt(s));
            
            node.left = deserialize(data, idx);
            node.right = deserialize(data, idx);
            
            return node;
        }
            
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            int[] idx = new int[1];
            idx[0] = 0;
            
            return deserialize(data, idx);
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
    
    
    

Log in to reply
 

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