Using lower and upper bound to deserialize BST, can handle INT_MAX and INT_MIN


  • 1
    X
    public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            inorder(root, sb);
            return sb.toString();
        }
        
        private void inorder(TreeNode node, StringBuilder sb) {
            if (node == null) {
                return;
            }
            sb.append(node.val).append(',');
            inorder(node.left, sb);
            inorder(node.right, sb);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data == null || data.length() == 0) {
                return null;
            }
            String[] strs = data.split(",");
            return buildTree(strs, new int[1], null, null);
        }
        private TreeNode buildTree(String[] strs, int[] pos, Integer min, Integer max) {
            if (pos[0] == strs.length) {
                return null;
            }
            int val = Integer.valueOf(strs[pos[0]]);
            if(min != null && val < min || max != null && val > max) {
                return null;
            }
            TreeNode root = new TreeNode(val);
            pos[0]++;
            root.left = buildTree(strs, pos, min, val);
            root.right = buildTree(strs, pos, val, max);
            return root;
        }
    

Log in to reply
 

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