normal pre-order for Serialize, the idea of 255 for Deserialize without "null", java


  • 0
    Z
    public String serialize(TreeNode root) {
        
        if (root == null) return "";
        StringBuilder ret = new StringBuilder();
        Stack<TreeNode> stack = new Stack<>();
        
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            ret.append(",").append(node.val);
            
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        }
        
        return ret.substring(1);
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) return null;
        String[] ds = data.split(",");
        
        Stack<TreeNode> stack = new Stack<>();
        TreeNode root = new TreeNode(Integer.parseInt(ds[0]));
        stack.push(root);
        
        for (int i = 1; i < ds.length; i ++) {
            TreeNode node = stack.peek();
            int temp = Integer.parseInt(ds[i]);
            
            if (temp < node.val) {
                node.left = new TreeNode(temp);
                stack.push(node.left);
            }
            else {
                while (!stack.isEmpty() && temp > stack.peek().val) node = stack.pop();
                node.right = new TreeNode(temp);
                stack.push(node.right);
            }
        }
        return root;
    }
    

Log in to reply
 

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