leetcode第113题:路径总和 II
https://leetcode-cn.com/problems/path-sum-ii/
【题目】
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
【思路】
本题和【T123-路径总和】类似,只是需要保存满足条件的路径。
解题思路和上一题稍微有点不同,如果当前节点为NULL,则返回;如果当前节点是叶子节点,则判断是否和sum相等,相等则添加路径;其他情况,继续递归遍历左子树和右子树(即使为空也没关系,因为有判断,不会error)。
【代码】
python版本
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
res = []
self.get_path_sum(root, [], res, sum)
return res
def get_path_sum(self, node, cur, res, sum):
if not node:
return
if not node.left and not node.right:
if node.val == sum:
cur.append(node.val)
res.append(cur)
return
cur.append(node.val)
self.get_path_sum(node.left, copy.copy(cur), res, sum-node.val)
self.get_path_sum(node.right, copy.copy(cur), res, sum-node.val)
C++版本
/**
* 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> cur;
get_path_sum(root, cur, res, sum);
return res;
}
void get_path_sum(TreeNode* node, vector<int> cur, vector<vector<int>>& res, int sum){
if(!node)
return;
if(!node->left && !node->right){
if(node->val == sum){
cur.push_back(node->val);
res.push_back(cur);
}
return;
}
cur.push_back(node->val);
get_path_sum(node->left, cur, res, sum-node->val);
get_path_sum(node->right, cur, res, sum-node->val);
}
};