[C++] 1 liner


  • 9
    class Solution {
    public:
        string tree2str(TreeNode* t) {
            return !t ? "" : to_string(t->val)
                            + (t->left ? "(" + tree2str(t->left) + ")" : t->right ? "()" : "")
                            + (t->right ? "(" + tree2str(t->right) + ")" : "");
        }
    };
    

    Full Size

    class Solution {
    public:
        string tree2str(TreeNode* t) {
            if (!t) return "";
            string s = to_string(t->val);
    
            if (t->left) {
                s += "(" + tree2str(t->left) + ")";
            }
            else if (t->right) {
                s += "()";
            }
            
            if (t->right) {
                s += "(" + tree2str(t->right) + ")";
            }
    
            return s;
        }
    };
    

Log in to reply
 

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