二叉树中和为某一值的路径
2018-03-25 10:10
162 查看
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
这题经常出错,首先要搞清楚递归函数中每个值的定义,root代表当前寻找的节点,expectNumber代表之前所有节点的和与目标和的差值。class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> res;
vector<int> path;
if(!root)
return res;
FindPath(root,expectNumber,res,path);
return res;
}
//root代表目前要寻找的节点,expectNumber表示目标值减去之前所有节点的和
void FindPath(TreeNode* root,int expectNumber,vector<vector<int>>& res,vector<int>& path){
if(!root||expectNumber<0)
return;
path.push_back(root->val);
if(expectNumber==root->val&&!root->left&&!root->right)
{
res.push_back(path);
path.pop_back();//这里一定要pop,不然return之后path里面的节点就会多出一个
return;
}
FindPath(root->left,expectNumber-root->val,res,path);
FindPath(root->right,expectNumber-root->val,res,path);
path.pop_back();
}
};
这题经常出错,首先要搞清楚递归函数中每个值的定义,root代表当前寻找的节点,expectNumber代表之前所有节点的和与目标和的差值。class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> res;
vector<int> path;
if(!root)
return res;
FindPath(root,expectNumber,res,path);
return res;
}
//root代表目前要寻找的节点,expectNumber表示目标值减去之前所有节点的和
void FindPath(TreeNode* root,int expectNumber,vector<vector<int>>& res,vector<int>& path){
if(!root||expectNumber<0)
return;
path.push_back(root->val);
if(expectNumber==root->val&&!root->left&&!root->right)
{
res.push_back(path);
path.pop_back();//这里一定要pop,不然return之后path里面的节点就会多出一个
return;
}
FindPath(root->left,expectNumber-root->val,res,path);
FindPath(root->right,expectNumber-root->val,res,path);
path.pop_back();
}
};
相关文章推荐
- 二叉树中找出和为某一值的所有路径
- 求二叉树中和为某一值的路径
- [程序猿面试题精选100题]4.二叉树中和为某一值的全部路径
- 二叉树中和为某一值的路径
- 剑指offer——二叉树中和为某一值得路径
- 剑指offer:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 面试题25:二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值得路径 java
- 面试题 25: 二叉树中和为某一值的路径
- 剑指offer之面试题25:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 1368:二叉树中和为某一值的路径 @jobdu
- java之二叉树和为某一值的路径
- 剑指Offer_24_二叉树中和为某一值的路径
- 面试题(三十四)二叉树中和为某一值的路径
- 【从零单排之微软面试100题系列】04之二叉树中和为某一值的路径
- 《剑指offer》-二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径