标签:
113. Path Sum II
Total Accepted: 80509 Total Submissions: 284188 Difficulty: MediumGiven a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum
= 22,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;//存放满足要求的路径
vector<int> cur;//当前路径
if(root==NULL)return result;
DFS(result,cur,root,sum);//深度搜索
return result;
}
void DFS(vector<vector<int>> &result,vector<int> &cur,TreeNode* root,int sum)
{
if(root==NULL)return;
if(root->left==NULL&&root->right==NULL)//到达叶子节点,形成合法路径,这时候再对路径进行验证
{
cur.push_back(root->val);//叶子节点纳入当前路径
if(sumOfPath(cur)==sum)//检验路径是否满足约束
result.push_back(cur);
cur.pop_back();//弹出当前路径末端数据并返回
return;
}
else
{
cur.push_back(root->val);//中序遍历的构架
DFS(result,cur,root->left,sum);
DFS(result,cur,root->right,sum);
cur.pop_back();//某一根节点的子节点搜索完毕,末端数据弹出,返回上一层
}
}
int sumOfPath(vector<int> &dataSet)//求取路径和
{
int sum=0;
for(int i=0;i<dataSet.size();i++)
{
sum+=dataSet[i];
}
return sum;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum)
{
List<List<Integer>> result=new ArrayList<List<Integer>>();//List接口变量用的ArrayList类对象实例化
List<Integer> temp=new ArrayList<Integer>();
if(root==null)return result;
DFS(result,temp,root,sum);
return result;
}
void DFS(List<List<Integer>> result,List<Integer> temp,TreeNode root,int sum)
{
if(root==null)return;
if(root.left==null&&root.right==null)
{
temp.add(root.val);
if(sumOfPath(temp)==sum)
result.add(new ArrayList(temp));//一定要注意
temp.remove(temp.size()-1);
return;
}
else
{
temp.add(root.val);
DFS(result,temp,root.left,sum);
DFS(result,temp,root.right,sum);
temp.remove(temp.size()-1);
}
}
int sumOfPath(List<Integer> temp)
{
int sum=0;
for(int i=0;i<temp.size();i++)
{
sum+=temp.get(i);
}
return sum;
}
}
【LeetCode】113. Path Sum II 基于Java和C++的解法及分析
标签:
原文地址:http://blog.csdn.net/jin_kwok/article/details/51356502