113. Path Sum II

来源:互联网 发布:网络连接修复工具 编辑:程序博客网 时间:2024/05/18 03:26

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]



找出和等于sum的全部路径,这里的路径是根节点到叶节点的路径。使用dfs可轻松破之。


代码:

class Solution{public:vector<vector<int>> pathSum(TreeNode* root, int sum){vector<int> path;dfs(root, 0, sum, path);return res;}private:vector<vector<int>> res;void dfs(TreeNode* root, int sum, int target, vector<int> path){if(!root){return;}path.push_back(root->val);sum += root->val;if(!root->left && !root->right){if(sum == target){res.push_back(path);}return;}dfs(root->left, sum, target, path);dfs(root->right, sum, target, path);}};


原创粉丝点击