Share my clean c++ solution using DFS [13ms]


  • 0
    M
    class Solution {
    public:
        void DFS(TreeNode* node,vector<int> path, vector<vector<int>>& out, int sum_so_far, int sum)
        {
        	if (!node)
    		return ;
        	sum_so_far += node->val;
        	path.push_back(node->val);
        	if (sum_so_far == sum && !node->left && !node->right)
        	{
        		out.push_back(path);
        		return ;
        	}
        	
        	DFS(node->left,  path, out, sum_so_far, sum);
        	DFS(node->right, path, out,sum_so_far, sum);
        }
    
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
    	vector<vector<int>> out;
    	vector<int> path;
    	DFS(root,path,out,0, sum);
    	return out;
    }
    };
    

Log in to reply
 

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