其他分享
首页 > 其他分享> > 113. 路径总和 II

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;
};

标签:right,TreeNode,cur,val,II,113,path,总和,left
来源: https://blog.csdn.net/qq_43287931/article/details/121498393