Path Sum II
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]
]
思路:这道题和上一道题Path Sum很相似,但是这就要求输出所有可能的路径了,而不是判断这条路径的值之和是否等于给定值。当前序遍历的方式访问到某一结点时,我们把该节点添加到路径上,并累加该节点的值。如果该结点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径符合要求,则将这一路径放入一序列中。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父结点。因此我们在函数推出前要在路径上删除当前结点饼减去当前结点的值,以确保返回父结点时刚好是从根结点到父结点的路径。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void FindPath(TreeNode *root,int sum,int ¤tSum,vector<int> &path,vector<vector<int> >&result) { currentSum+=root->val; path.push_back(root->val); bool isLeaf=root->left==NULL && root->right==NULL; if(currentSum==sum && isLeaf) { result.push_back(path); } if(root->left!=NULL) FindPath(root->left,sum,currentSum,path,result); if(root->right!=NULL) FindPath(root->right,sum,currentSum,path,result); currentSum-=root->val; path.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > result; if(root==NULL) return result; vector<int> path; int currentSum=0; FindPath(root,sum,currentSum,path,result); return result; } };