21ms easy pre-order serialization in Java


  • 0
    I
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        preOrderEncode(root, sb);
        String treeString = sb.toString();
        return treeString.substring(0, treeString.length() - 1);  // get rid of trailing comma
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) { 
        String[] nodeStrings = data.split(",");
        TreeNode root = stringToTreeNode(nodeStrings[0]);
        _deserialize(root, nodeStrings, new MutableInteger(1));
        return root;
    }
    
    private void _deserialize(TreeNode root, String[] nodeStrings, MutableInteger nodeIdx) {
        if (nodeIdx.value < 0 || nodeIdx.value >= nodeStrings.length) {
            return;
        }
        
        if (root == null) {
            return;
        }
        
        TreeNode left = stringToTreeNode(nodeStrings[nodeIdx.value++]);
        root.left = left;
        _deserialize(root.left, nodeStrings, nodeIdx);
        
        //
        TreeNode right = stringToTreeNode(nodeStrings[nodeIdx.value++]);
        root.right = right;
        _deserialize(root.right, nodeStrings, nodeIdx);
    }
    
    
    private void preOrderEncode(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("null,");
            return;
        }
        
        sb.append(root.val + ",");
        
        preOrderEncode(root.left, sb);
        preOrderEncode(root.right, sb);
    }
    
    private TreeNode stringToTreeNode(String s) {
        if (s.equals("null")) {
            return null;
        }
        return new TreeNode(Integer.parseInt(s));
    }
    
    private class MutableInteger {
        int value;
        public MutableInteger (int value) { this.value = value; }
    }

Log in to reply
 

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