LeetCode Path Sum II (DFS)

时间:2023-03-08 23:26:49
LeetCode Path Sum II  (DFS)

题意:

  给一棵二叉树,每个叶子到根的路径之和为sum的,将所有可能的路径装进vector返回。

思路:

  节点的值可能为负的。这样子就必须到了叶节点才能判断,而不能中途进行剪枝。

 /**
* 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) {
if(root==NULL) return ans;
DFS(root,,sum,tmp);
return ans;
}
void DFS(TreeNode* t,int n,const int& sum,vector<int>& num)
{
num.push_back(t->val);
n+=t->val; if(t->left==NULL&&t->right==NULL)
{
if(n==sum) ans.push_back(num);
}
else
{
if(t->left) DFS(t->left,n,sum,num);
if(t->right) DFS(t->right,n,sum,num);
}
num.pop_back();
}
private:
vector<vector<int>> ans;
vector<int> tmp;
};

AC代码