Article directory
1. The topic
hint:
- The total number of nodes in the tree is in the range [0, 5000]
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
2. Ideas
Looking back at the idea, dfs first adds the current element, and then judges whether the temp
array so far satisfies sum=target
a condition, and if not, continues to recursively traverse the left subtree and the right subtree. Notice! ! !When both the left subtree and the right subtree are empty, that is, the current node is a leaf node, and the judgment is over! ! Take temp
out the last (leaf) node just stored in the array, and the next step is to recurse the [sibling node] of the node just now.!!
Similar backtracking topics:
[LeetCode46] Full permutation (DFS)
[LeetCode39] Combination sum (backtracking method)
[LeetCode494] Target sum (violent search dfs or dp)
[LeetCode17] Letter combination of phone numbers (DFS backtracking)
3. Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>>ans;
vector<int>temp;
int sum = 0;
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root, target);
return ans;
}
void dfs(TreeNode* root, int target){
if(root == NULL){
return;
}
temp.push_back(root->val);
sum += root->val;
//到根节点了,并且sum满足条件
if(root->left == NULL && root->right == NULL && sum == target){
ans.push_back(temp);
}
dfs(root->left, target);
dfs(root->right, target);
//当左右孩子都为空的节点时,就把temp里最后的节点弹出,dfs弹出节点的兄弟节点
temp.pop_back();
sum -= root->val;
}
};