15 lines Java solution, super clean


  • 0

    Use the preorder way.
    To avoid using 'pos' for a global variable, you may use a LinkedList for the deserialize part.

        public String serialize(TreeNode root) {
            if (root == null) {return "#";}
            return root.val + " " + serialize(root.left) + " " + serialize(root.right);
        }
    
        int pos = -1;
        public TreeNode deserialize(String data) {
            return helper(data.split(" "));
        }
        
        public TreeNode helper(String[] data) {
            pos++;
            if (data[pos].equals("#")) {return null;}
            TreeNode root = new TreeNode(Integer.valueOf(data[pos]));
            root.left = helper(data); root.right = helper(data);
            return root;
        }
    

Log in to reply
 

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