Easy understand C++ solution


  • 0
    C
        class Solution {
        public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string>result;
            string tmp;
            dfs(root,tmp,result);
            return result;
        }
       private:
        void dfs(TreeNode* root,string tmp,vector<string>& result){
            if(root==nullptr)
                return;
            if(tmp.empty()){
                    tmp = to_string(root->val);
            }else
                tmp = tmp+"->"+to_string(root->val);
            if(root->left==nullptr && root->right==nullptr){
                result.push_back(tmp);
            }
            dfs(root->left,tmp,result);
            dfs(root->right,tmp,result);
            
        }
        
    };

Log in to reply
 

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