【Leetcode】【Medium】Path Sum II

时间:2022-01-21 18:41:58

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

解题:

实用递归的方法,题目很简单,每深一层递归,带入新计算出的需要求的sum值,递归函数需要四个入参:最终返回数组,当前已经经历的路径,当前需要的sum,已经结点指针

由于需要递归多个函数,刚开始为了防止“当前已经经历的路径”出现重复记载,因而没有形参没有使用指针,而完整的传入了整个数组,时间72ms

代码如下:

 /**
* Definition for binary tree
* 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> > ret;
vector<int> cur_nums;
pathSumTree(ret, cur_nums, root, sum);
return ret;
} void pathSumTree(vector<vector<int> > &ret, vector<int> cur_nums, TreeNode *root, int cur_sum) {
if (!root)
return; cur_nums.push_back(root->val);
if (!root->left && !root->right && cur_sum - root->val == )
ret.push_back(cur_nums); pathSumTree(ret, cur_nums, root->left, cur_sum - root->val);
pathSumTree(ret, cur_nums, root->right, cur_sum - root->val);
return;
}
};

但是将形参设置为指针后,代码运行时间大大减少了,因为传递指针比传递整个数组高效多了;

为了防止出现混乱,可以在每次路径考察结束后,将当前的结点从数组中pop出来,避免重复;

代码如下,这次只需要不到20ms:

 /**
* Definition for binary tree
* 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> > ret;
vector<int> cur_nums();
pathSumTree(ret, cur_nums, root, sum);
return ret;
} void pathSumTree(vector<vector<int> > &ret, vector<int> &cur_nums, TreeNode *root, int cur_sum) {
if (!root)
return; cur_nums.push_back(root->val);
if (!root->left && !root->right && cur_sum - root->val == ) {
ret.push_back(cur_nums);
cur_nums.pop_back();
return;
} pathSumTree(ret, cur_nums, root->left, cur_sum - root->val);
pathSumTree(ret, cur_nums, root->right, cur_sum - root->val);
cur_nums.pop_back();
return;
}
};