1、问题描述
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。一个有效的路径,指的是从根节点到叶节点的路径。样例
给定一个二叉树,和 目标值 = 5:
1
/ \
2 4
/ \
2 3
返回:
[
[1, 2, 2],
[1, 4]
]
2、实现思路
找到路径和为给定数值的路径,最后输出的是所有符合的路径,故需要一个二维数组,遍历每一条路径记录起来,长度为给定值的将路径加到二维数组中,遍历到叶子节点此路径结束,返回上一个节点时,删除最后一个节点,再往上返回节点时,删除最后一个节点。
3、代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<int> path;
vector< vector<int> > p;
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
// Write your code here
if(root==NULL) return p;
bianli(root,target);
return p;
}
void bianli(TreeNode *root, int target)
{ if(root==NULL) return;
path.push_back(root->val);
bianli(root->left,target);
bianli(root->right,target);
if(root->left==NULL&&root->right==NULL)
{ int a,n,i;
a=0;
n=path.size();
for(i=0;i<n;i++)
{ a=a+path[i];}
if(a==target) p.push_back(path);
} path.pop_back();
}
};
4、感想
利用了path.pop_back();删除最后一个节点,遍历每一条路径将路径记录到一维数组中,长度为给定值的将路径加到二维数组中,遍历到叶子节点此路径结束,返回上一个节点时,删除最后一个节点,再往上返回节点时,删除最后一个节点。
5946

被折叠的 条评论
为什么被折叠?



