文章目录
  1. 1. Path Sum II
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Path Sum II

题目

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]
]

思路

跟path sum思路一样,只不过这里要保存经过的路径。

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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>> result;
vector<int> cur;
pathSum(root,sum,cur,result);
return result;
}

void pathSum(TreeNode*root,int sum,vector<int>&cur,vector<vector<int>>& result){
if(!root)
return;
cur.push_back(root->val);
if(!root->left && !root->right){
if(root->val==sum){
result.push_back(cur);
}
}
pathSum(root->left,sum-root->val,cur,result);
pathSum(root->right,sum-root->val,cur,result);
cur.pop_back();
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param {TreeNode} root
# @param {integer} sum
# @return {integer[][]}
def pathSum(self, root, sum):
result=[]
cur=[]
self.hasPath(root,sum,cur,result)
return result

def hasPath(self,root,p,cur,result):
if not root:
return
cur.append(root.val)
if not root.left and not root.right:
if root.val==p:
result.append(cur)
self.hasPath(root.left,p-root.val,cur,result)
self.hasPath(root.right,p-root.val,cur,result)
cur.pop()

文章目录
  1. 1. Path Sum II
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题