给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

路径总和Ⅱ-47 - 图1

  1. Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
  2. Output: [[5,4,11,2],[5,8,4,5]]

示例 2:

路径总和Ⅱ-47 - 图2

  1. Input: root = [1,2,3], targetSum = 5
  2. Output: []

示例 3:

  1. Input: root = [1,2], targetSum = 0
  2. Output: []

提示:

  • -1000 ≤ Node.val ≤ 1000
  • -1000 ≤ targetSum ≤ 1000
  • 树中节点总数在范围 [0, 5000]

思路

先把根节点加入到path,然后进行左递归的DFS。

递归终止条件:访问到叶子节点(没有左右子树的节点)。

代码

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
  15. vector<vector<int>> answer;
  16. if( root == nullptr ) return answer;
  17. vector<int> path;
  18. path.emplace_back( root->val );
  19. targetSum -= root->val;
  20. dfs(root, targetSum, answer, path);
  21. return answer;
  22. }
  23. void dfs(TreeNode* node, int targetSum, vector<vector<int>>& answer, vector<int>& path) {
  24. // 1. Exit condition: leaf node
  25. if( node->left == nullptr && node->right == nullptr ) {
  26. if( 0 == targetSum ) {
  27. answer.emplace_back( path );
  28. return;
  29. }
  30. }
  31. // 2. Walk every node that not visited
  32. if( node->left != nullptr ) {
  33. path.emplace_back( node->left->val );
  34. dfs( node->left, targetSum - node->left->val, answer, path );
  35. path.pop_back();
  36. }
  37. if( node->right != nullptr ) {
  38. path.emplace_back( node->right->val );
  39. dfs( node->right, targetSum - node->right->val, answer, path );
  40. path.pop_back();
  41. }
  42. }
  43. };