二叉树的路径和
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。样例
给定一个二叉树,和 目标值 = 5:
返回:
[
[1, 2, 2],
[1, 4]
]标签
二叉树 二叉树遍历
code
/**
* 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<vector<int> > binaryTreePathSum(TreeNode *root, int target) {
// Write your code here
vector<vector<int> > result;
vector<int> order;
TreeNode *p=root;
int path=0;
if(root == NULL) {
return result;
}
else {
path = 0;
findPath(root, target, order, path, result);
return result;
}
}
void findPath(TreeNode *root, int target, vector<int> &order, int &path, vector<vector<int> > &result) {
path += root->val;
order.push_back(root->val);
if(path == target && (root->left==NULL&&root->right==NULL)) {
result.push_back(order);
}
if(root->left != NULL)
findPath(root->left, target, order, path, result);
if(root->right != NULL)
findPath(root->right, target, order, path, result);
path -= root->val;
order.pop_back();
}
};