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 and sum = 22,
return
给一个二叉树和一个数字sum,让你找出所有路径和为sum的路径,当然也可能没有,要解决这个问题,我们当然要递归遍历每条路径,对于一条路径,我们把遍历过的节点放到一个vector中,当遍历到节点i时,如果发现向下遍历不能找到这样的路径,就要回溯至它的父节点,同时vector中也要删除该节点。这是本题的唯一难点。c++的approach如下:
/**
* 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>> ret;
vector<int> temp;
helper(node, sum, ret, temp);
return ret;
}
void helper(TreeNode* node, int value, vector<vector<int>> ret, vector<int> temp){
if(!node)
return;
temp.push_back(node->val);
if(node->val-value == 0 && node->right == NULL && node->left == NULL)
ret.push_back(temp);
helper(node->left, value-node->val, ret, temp);
helper(node->right, value-node->val, ret, temp);
temp.pop();
}
};
本文介绍了一种算法,用于在给定的二叉树中寻找所有从根节点到叶子节点的路径,使得这些路径上的节点值之和等于指定的目标值。通过递归方法实现,并提供了详细的C++代码示例。
378

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



