basic recursive solution, easy to understand


  • 0
    J
    string tree2str(TreeNode* t) {
            if(!t) return "";
            return preorder(t);
        }
        
        string preorder(TreeNode* t) {
            if(!t) return "()";
            else if(!t->left && !t->right){
                return to_string(t->val);
            }
            else if(!t->left){
                string tmp = to_string(t->val) + "()(" + preorder(t->right) + ")";
                return tmp;
            }
            else if(!t->right){
                string tmp = to_string(t->val) + "(" + preorder(t->left) + ")";
                return tmp;
            }
            else{
                string tmp = to_string(t->val) + "(" + preorder(t->left) + ")" + "(" + preorder(t->right) + ")" ;
                return tmp;
            }
        }
    

Log in to reply
 

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