Probably the MOST CONCISE one in Java, without Queue / Stringbuilder etc.


  • 0

    Preorder + Recursion

        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
    S

    String[] tree = data.split(" ");

    This should only be done once and the performance will be much better. There is no need to do the split for each recursive call.


  • 0

    @hamster sure, your r right


  • 0
    Z

    You used global variables, which is not allowed in the question.


  • 0

    @zan020 ohhh? sorry I just copy it from my lintcode solution, the requirement may be different LOL


  • 0

    @monster-gump
    The overall DFS idea is clean and smart. It is easier than using queues(BFS).
    The global variable problem is not a big deal and can be solved easily. But from time complexity, it is a good habit to use StringBuilder or StringBuffer when you want to change a string frequently. In java, String is immutable. That means when you call string a + string b. It will create a new string object since you cannot change the string itself. When the size of this problem becomes bigger, your code will create a lot of new strings. On the contrary, StringBuilder and StringBuffer are mutable. You can change them without creating any new object.


  • 0

    @Nakanu thx a lot, I haven't notice that lol


Log in to reply
 

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