leetcode 113. Path Sum II

Given a binary tree and a target sum, find all paths from the root node to the leaf nodes whose sum is equal to the given target sum.

Explanation: A leaf node is a node that has no child nodes.

Example:
Given the following binary tree, and the target sum  sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return:

[
   [5,4,11,2],
   [5,8,4,5]
] 


I haven't used dfs for a long time. Tree traversal is often combined with dfs;
temp is used to save the value of each path. When the value is the same as the sum value, the value of temp is pushed into
each traversal of dfs in ans Abort and leaf node, when accessing the leaf node, you need to pop the leaf node.
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> ans;
13     vector<int> temp;
14     void dfs(TreeNode* root, int sum){
15         if(root == NULL) return;
16         temp.push_back(root->val);
17         if(root->val == sum && root->right == NULL && root->left == NULL)
18             ans.push_back(temp);
19         dfs(root->left, sum-root->val);
20         dfs(root->right, sum-root->val);
21         temp.pop_back();
22     }
23     vector<vector<int>> pathSum(TreeNode* root, int sum) {
24         dfs(root, sum);
25         return ans;
26     }
27 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061946&siteId=291194637