clean Java solution beats 98%


  • 1
    Z

    The idea is simple: traversal the tree in preorder and add each number to a string.
    I use a special character '|' to cut numbers so that when decoding the string I can distinguish each number clearly. I use '#' to represent null elements.
    This solution also works for Problem 297.

    public class Codec {
        int start = 0;
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if (root == null) {
                return "#";
            }
            return String.valueOf(root.val) + "|" + serialize(root.left) + "|" + serialize(root.right);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data.charAt(start) == '#') {   // if the node is null
                start++;    // jump over the '|' character
                return null;
            }
            int end = start;
            while (end == data.length() || data.charAt(end) != '|') {
                end++;
            }
            String num = data.substring(start, end);   // read a single number
            TreeNode node = new TreeNode(Integer.valueOf(num));
            start = end;
            start++; node.left = deserialize(data);
            start++; node.right = deserialize(data);
            return node;
        }
    }
    

  • 0
    A

    @zhuohanx Can you please explain the function of start and end in your deserialize method?


Log in to reply
 

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