Short and clear recursive Java solution


  • 20
    M
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) 
    {
        if(root == null) return "#";
        
        return "" + root.val + " " + serialize(root.left) + " " + serialize(root.right);
    }
    
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) 
    {
        return build(new Scanner(data));
    }
    
    private TreeNode build(Scanner sc)
    {
        if(!sc.hasNext()) return null;
        String tk = sc.next();
        if(tk.equals("#")) return null;
        
        TreeNode root = new TreeNode(Integer.parseInt(tk));
        root.left = build(sc);
        root.right = build(sc);
        
        return root;
    }

Log in to reply
 

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