原题目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
题目大意
该题给定一个二叉树和一个targetSum,从该树中找出一条从根节点到叶节点的路径,使得该路径上每个节点的值的总和等于该targetSum,需要注意的是,此处要求的是到叶节点的路径,叶子节点也就是指左右节点都为空的节点。
解题思路
看到这道题第一想法就是应该要用优先遍历算法(BFS或者DFS),因为该题要求找出所有路径,所以遍历是肯定需要的。最开始的时候,犯了一个小错误,认为只要某条路径的节点值之和大于targetSum就没有继续从这条路遍历下去的需要了,后来发现题目没有说明叶子节点的值为正,有可能会存在负值,所以,在你顺着该路径遍历到最后一个节点(叶子节点)之前,是无法得知该路径的节点值之和会不会等于targetSum的,所以这要求我们遍历所有的从根节点到叶子节点的路径,既然是遍历,那么BFS和DFS也就都可以使用了,接下来,我们来讨论一下BFS和DFS两种解决办法。
方法一: DFS
函数声明如下:
void DFS_find_path(vector<vector<int>>& res, TreeNode* node, int nowSum, int targetSum, vector<int> &path)
函数实现大体思路:
我们从根节点出发往下遍历,每次向遍历到一个节点(为空就直接返回),当前节点之和nowSum加上该节点值,同时将该值插入队列path中,然后判断一下nowSum是否等于targetSum且该节点是否为叶子节点,如果是,那么将path插入到结果队列,否则继续往下遍历。注意,此处path采用引用传参,所以需要在递归返回时把当前path尾部pop出来,保持path进来的状态。(也可以不用引用传参,那就不用pop了,但会导致在参数传递这一块多一些时间消耗)
函数代码实现如下:
/* 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> > res;
vector<int> path;
DFS_find_path(res, root, 0, sum, path);
return res;
}
void DFS_find_path(vector<vector<int> >& res, TreeNode* node, int nowSum, int targetSum, vector<int>& path) {
if (!node) return;
nowSum += node->val;
path.push_back(node->val);
if (nowSum == targetSum && node->left == NULL && node->right == NULL) {
res.push_back(path);
return;
} else {
DFS_find_path(res, node->left, nowSum, targetSum, path);
DFS_find_path(res, node->right, nowSum, targetSum, path);
}
path.pop_back();
}
};
方法二: DFS
BFS的遍历相当于将该树分层,然后每一次遍历一整层的节点,直至遍历到叶子节点,这个算法可以不用使用递归,但有一个问题是,需要对每一个节点维护一条队列,队列存储到该节点的路径,所以可能会有更多的空间消耗和时间消耗。
代码实现如下:
struct BFSnode {
TreeNode* node;
vector<int> path;
int nowSum;
BFSnode(TreeNode* node_, int nowSum_) {
node = node_;
nowSum = nowSum_;
}
bool isleaf() {
return node->left == NULL && node->right == NULL;
}
};
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
if (root == NULL) return res;
vector<int> path;
queue<BFSnode> que;
BFSnode rootNode = BFSnode(root, root->val);
rootNode.path.push_back(root->val);
que.push(rootNode);
while(!que.empty()) {
BFSnode BN = que.front();
que.pop();
if (BN.nowSum == sum && BN.isleaf()) {
res.push_back(BN.path);
} else {
if (BN.node->left) {
BFSnode BNleft = BFSnode(BN.node->left, BN.nowSum+BN.node->left->val);
BNleft.path = BN.path;
BNleft.path.push_back(BN.node->left->val);
que.push(BNleft);
}
if (BN.node->right) {
BFSnode BNright = BFSnode(BN.node->right, BN.nowSum+BN.node->right->val);
BNright.path = BN.path;
BNright.path.push_back(BN.node->right->val);
que.push(BNright);
}
}
}
return res;
}
};