Java: Use recursion to serialize, deserialize from tail to head - not requiring global state variables


  • 0
    R
    public String serialize(TreeNode root) {
            if (root == null) return ",null";
            return "," + root.val + serialize(root.left) + serialize(root.right); 
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data == null || data.length() == 0 || data.trim().isEmpty()) return null;
            String[] nodes = data.split(",");
    
            TreeNode parent = null;
            int n = data.length();
    
            while (n >= 1) {
                int parentIndex = n / 2;
                parent = parseNum(parentIndex, nodes);
                if (parent != null) {
                    parent.left = parseNum(n-1, nodes);
                    parent.right = parseNum(n, nodes);
                }
    
                n -= 2;
            }
            return parent;
        }
        
        private TreeNode parseNum(int index, String[] nodes) {
            
            if (index > nodes.length || index < 1) return null;
            
            String node = nodes[index-1];
            if (!node.equals("null") && !node.isEmpty()) {
                int val = Integer.parseInt(node);
                return new TreeNode(val);
            }
            return null;
        }
    
    

  • 0

    Can't handle case like [1,null, 2, null,3,null, 4,null,5,null, 6], I guess it only works for complete binary tree?


Log in to reply
 

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