113. 路径总和 II

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution 
{
public:
	
	void traversal(TreeNode* cur, int count)
	{
		if(cur->left == nullptr && cur->right == nullptr && count == 0)
		{
			res.push_back(path);
			path.clear();
			return ;
		}
		
		if(cur->left == nullptr && cur->right == nullptr)
		{
			return ;
		}
		
		if(cur->left)
		{
			path.push_back(cur->left->val);
			count -= cur->left->val;
			traversal(cur->left, count);
			count += cur->left->val;
			path.pop_back();
		}
		if(cur->right)
		{
			path.push_back(cur->right->val);
			count -= cur->right->val;
			traversal(cur->right, count);
			count += cur->right->val;
			path.pop_back();
		}

		return ;
	}

	vector<vector<int>> pathSum(TreeNode* root, int targetSum) 
	{	
		if(root == nullptr)
		{
			return res;
		}
		
        res.clear();
        path.clear();
        path.push_back(root->val);
		traversal(root, targetSum - root->val);
		
		return res;
	}

private:

	vector<vector<int>> res;
	vector<int> path;
};
上一篇:113、函数指针?


下一篇:451. 根据字符出现频率排序(每日随记)