问题描述:
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,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
问题分析:
如题所述,很容易可以想到使用深度优先搜索遍历二叉树,然后维护一个数组,用来保存从根节点到当前节点所经过的路径的节点值,当遍历到叶子节点时,对访问路径所经过的节点的值求和,若与欲求的目标值相等,则为目标路径,否则返回,尝试下一条路径。
具体实现:
/**
* 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> pathSum(TreeNode* root, int sum) {
vector> res;
vector list;
searchSum(res,root,list,0,sum);
}
void searchSum(vector> &res, TreeNode* root, vector list, int val, int sumTarget)
{
if(res==NULL)
{
if(val==sumTarget)
res.pushback(list);
return;
}
list.pushback(root->val);
val = val+root->val;
searchSum(res, root->left,list,val,sumTarget);
searchSum(res, root->right,list,val,sumTarget);
}
};
本文介绍了一种算法,用于寻找二叉树中所有从根节点到叶子节点且路径节点值之和等于给定目标值的路径。通过深度优先搜索遍历二叉树并维护路径节点值。
8万+

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



