16 lines in Java, pretty simple solution in PreOrder for any BT


  • 0

    The idea and code are pretty simple:

    1. get the PreOrder sequence of BT
      1.1 save all nodes
      1.2 save its children (even when they are null), but for the null nodes, we don't save their children
    2. deserialize the sequence back
      2.1 use a global variable to help, split the sequence into array
      2.2 construct the tree step by step, which can make use of the "null" nodes
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if (root == null) {return "null";}
            return String.valueOf(root.val) + "," + serialize(root.left) + "," + serialize(root.right);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            return helper(data.split(","));
        }
        
        int pos = -1;
        public TreeNode helper(String[] data) {
            pos++;
            if (data[pos].equals("null")) {return null;}
            TreeNode root = new TreeNode(Integer.parseInt(data[pos]));
            root.left = helper(data);
            root.right = helper(data);
            return root;
        }
    

  • 0
    L

    The requirement says "Note: Do not use class member/global/static variables to store states."
    So you may pass the variable as function argument.


  • 0

    @lfzh123 sure, you r rgiht.


Log in to reply
 

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