给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
这个题需要用深度优先搜索,如果搜索到某个节点是叶子结点且之前的所有节点之和为sum,那就添加路径。
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> out;
DFS(root, out, res, sum);
return res;
}
void DFS(TreeNode* root, vector<int>& out, vector<vector<int>>& res, int sum){
if(!root) return;
out.push_back(root->val);
if(sum==root->val && !root->left && !root->right)
res.push_back(out);
DFS(root->left, out, res, sum-root->val);
DFS(root->right, out, res, sum-root->val);
out.pop_back();
}
};
python3源代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
l = []
temp = []
self.isPathSum(root, sum, l, temp)
return l
def isPathSum(self, root, sum, l, temp):
if root==None:
return
temp.append(root.val)
if root.left==None and root.right==None and sum==root.val:
l.append(copy.deepcopy(temp))
self.isPathSum(root.left, sum-root.val, l, temp)
self.isPathSum(root.right, sum-root.val, l, temp)
temp.pop()