leetcode 437. Path Sum III

Given a binary tree, each node of it holds an integer value.

Find the paths and the total number of paths equal to the given number.

The path does not need to start at the root node nor end at the leaf node, but the path direction must be downward (only from parent node to child node).

The binary tree does not exceed 1000 nodes, and the node value range is an integer of [-1000000, 1000000].

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. and paths equal to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11 

ideas:
  • Use dfs() twice, dfs() is used to find the number of paths extending from a node, and the path equivalent is equal to sum, dfs1() is used to traverse each node
  • The superposition of two dfs functions can be used to find the requirements in the question
 1 class Solution {
 2 public:
 3     void dfs(TreeNode* root, int sum, int& cnt){
 4         if(root == NULL) return;
 5         if(root->val == sum) cnt++;
 6         dfs(root->left, sum-root->val, cnt);
 7         dfs(root->right, sum-root->val, cnt);
 8     }
 9     
10     void dfs1(TreeNode* root, int sum, int& cnt){
11         if(root == NULL) return;
12         dfs(root, sum, cnt);
13         dfs1(root->left, sum, cnt);
14         dfs1(root->right, sum, cnt);
15     }
16     int pathSum(TreeNode* root, int sum) {
17         int cnt = 0;
18         dfs1(root, sum, cnt);
19         return cnt;
20     }
21 };

 

Guess you like

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