- 34 二叉树中和为某一值的路径
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof - 输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
- 示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
解题思路:【c++】深度优先搜索+先序遍历:从根节点开始先序遍历。定义全局变量path,sumList分别存储当前路径及满足条件的路径。递归参数cur节点与当前路径总和与目标值的差值curSum,若cur==NULL,返回空,否则,将cur值val加入path,当前差值curSum=sum-val,判断cur为叶子结点(左右子节点均为NULL)且curSum==0代表已找到满足条件的路径,将path加入到sumList中。递归调用遍历其左子树与右子树,将已遍历的节点从path中删去。
// 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<int> path;
vector<vector<int>> sumList;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
dfs(root, sum);
return sumList;
}
void dfs(TreeNode *root, int cur_sum){
if (root==NULL) return;
// cout<< root->val<<endl;
path.push_back(root->val);
cur_sum = cur_sum - root->val;
// cout<<"cur:"<< cur_sum<<endl;
// cout<<"size:"<<path.size()<<endl;
if (cur_sum == 0 && (root->left == NULL) && (root->right ==NULL))
{
sumList.push_back(path);
}
dfs(root->left, cur_sum);
dfs(root->right, cur_sum);
path.pop_back(); //删去最末节点
}
};
# python 3
# 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: TreeNode, sum: int) -> List[List[int]]:
path = [] #记录当前路径
sumList = [] #记录满足条件的路径
def dfs(root, curSum):
if not root: return
#print (root.val) #先序遍历
path.append(root.val)
curSum = curSum - root.val
#记录路径不能直接执行 res.append(path) ,(因为将 path 对象加入了 res ,后续 path 改变时, res 中的 path 对象也会随之改变。),应该执行 res.append(list(path)) ,相当于复制了一个 path 并加入到 res
if curSum==0 and not root.left and not root.right:
sumList.append(list(path))
dfs(root.left, curSum)
dfs(root.right, curSum)
path.pop() #需要删除路径
dfs(root, sum)
return sumList
Notes: python3中记录路径不能直接执行 res.append(path) ,(因为将 path 对象加入了 res ,后续 path 改变时, res 中的 path 对象也会随之改变。)应该执行 res.append(list(path)) ,相当于复制了一个 path 并加入到 res。