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]
]
class Solution { public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > ans; vector<int> temp; if (root!=NULL) pathSumUtil(root , sum , 0 , ans , temp); return ans; } private: void pathSumUtil(TreeNode *root, int sum , int cur , vector<vector<int> > &ans , vector<int> &temp) { temp.push_back(root->val); if(root->left==NULL && root->right==NULL) { if( cur+root->val == sum ) ans.push_back(temp); } else { if(root->left!=NULL) pathSumUtil( root->left, sum, cur+root->val, ans , temp ); if(root->right!=NULL) pathSumUtil( root->right, sum, cur+root->val, ans , temp ); } temp.pop_back(); } };
原文地址:http://blog.csdn.net/keyyuanxin/article/details/44115267