Concise Java solution, 21ms


  • 3
    A
    public class Codec {
    
        public String serialize(TreeNode root) {
            if (root == null) {
                return "#";
            }
            return String.valueOf(root.val) + " " + serialize(root.left) + " " + serialize(root.right);
        }
    
        int desPos;
    
        public TreeNode deserialize(String data) {
            desPos = -1;
            return desHelper(data.split(" "));
        }
    
        private TreeNode desHelper(String[] strs) {
            desPos++;
            if (strs[desPos].equals("#")) {
                return null;
            }
            TreeNode node = new TreeNode(Integer.parseInt(strs[desPos]));
            node.left = desHelper(strs);
            node.right = desHelper(strs);
            return node;
        }
    }
    

  • 0

    Thanks a lot, really beautiful and concise one!
    This one is the version I am looking for, without StringBuilder or Tokenizer etc.

    My idea is the same like yours, somehow it doesn't work at the first time, but now I make it works and probably more concise than your code XD

        String data = "";
         
        public String serialize(TreeNode root) {
            // write your code here
            if (root == null) {
                data += "# ";
            }
            else {
                data += root.val + " ";
                serialize(root.left);
                serialize(root.right);
            }
            return data;
        }
        
        int pos = -1;
        public TreeNode deserialize(String data) {
            // write your code here
            pos++;
            String[] tree = data.split(" ");
            if (tree[pos].equals("#")) {
                return null;
            }
            TreeNode root = new TreeNode(Integer.parseInt(tree[pos]));
            root.left = deserialize(data);
            root.right = deserialize(data);
            
            return root;
        }
    

  • 0
    This post is deleted!

Log in to reply
 

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