题目描述
给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum的路径,
例如:
给出如下的二叉树,sum=22,
5
/
4 8
/ /
11 13 4
/ /
例如:
给出如下的二叉树,sum=22,
5
/
4 8
/ /
11 13 4
/ /
7 2 5 1
返回
[
[5,4,11,2],
[5,8,4,5]
]
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 andsum = 22,
return
[
[5,4,11,2],
[5,8,4,5]
]
返回
[
[5,4,11,2],
[5,8,4,5]
]
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 andsum = 22,
5
/
4 8
/ /
11 13 4
/ /
/
4 8
/ /
11 13 4
/ /
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
示例2
输出
复制[[1,2]]
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector <vector <int>> vv;
vector <int> v;
pathSum_Aux(root,sum,v,vv);
return vv;
}
void pathSum_Aux(TreeNode *root,int sum,vector <int> v,vector<vector<int>>&vv){
if (root==NULL)
return ;
v.push_back(root->val);
if (root->left ==NULL && root->right==NULL &&sum -root->val==0){
vv.push_back(v);
}
pathSum_Aux(root->left, sum-root->val, v,vv);
pathSum_Aux(root->right,sum-root->val,v,vv);
}
};
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
vector <vector<int>>res;
void dfspath(TreeNode *root,int num,vector<int>v){
if (!root)return ;
v.push_back(root->val);
if (root->left ==nullptr && root->right==nullptr){
if (num==root->val )res.push_back(v);
}
dfspath(root->left,num-root->val,v);
dfspath(root->right,num-root->val,v);
}
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector <int>v;
dfspath(root, sum, v);
return res;
}
};
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @param sum int整型
# @return int整型二维数组
#
class Solution:
def pathSum(self , root , sum ):
# write code here
if not root:
return []
res=[]
def helper(root,remain,temp=[]):
temp_=temp+[root.val]
remain_=remain-root.val
if remain_==0 and not root.left and not root.right:
res.append(temp_)
return
if root.left:
helper(root.left,remain_,temp_)
if root.right:
helper(root.right,remain_,temp_)
helper(root,sum)
return res