[606. Construct String from Binary Tree] C++_DFS method


  • 0
    class Solution {
    public:
    string tree2str(TreeNode* t) {
        if(t == nullptr) return "";
        string res = "";
        dfs(t, res);
        res = res.substr(1);
        res.pop_back();
        return res;
    }
    
    void dfs(TreeNode* t, string& res){
        if(t == nullptr) return;
        res += '(' + to_string(t->val);
        if(!t->left && !t->right){
            res += ')';
            return;
        }
        if(t->left){
            dfs(t->left, res);
        }else{
            res += "()";
        }
        if(t->right){
            dfs(t->right, res);
        }
        res += ')';
    }
    };

Log in to reply
 

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