5 lines of C++ with comments


  • 0
    Y

    This is probably not the most efficient way about it, but with a tail recursive helper I think this should perform really well:
    Let me know what you guys think:

    class Solution 
    {
        public:
        string tree2str(TreeNode* t) 
        {
            // Null nodes are mapped to an empty string
            if(!t) { return ""; }
            
            // Leaf nodes need not have their children paranthesized
            if(!(t->left) && !(t->right)) { return to_string(t->val); }
    
            // Every other node -- root(left | ())(right | "")
            return to_string(t->val) + 
                (t->left ? "(" + tree2str(t->left) + ")" : "()") + 
                (t->right ? "(" + tree2str(t->right) + ")": "");
        }
    };
    

Log in to reply
 

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