Programmer interview golden classic-interview questions 04.12. Summation path

1. Topic introduction

Given a binary tree, each node contains an integer value (the value is either positive or negative). Design an algorithm to print the number of all paths whose sum of node values ​​is equal to a given value. Note that the path does not necessarily have to start or end from the root node or leaf node of the binary tree, but its direction must be downward (only from the parent node to the child node).

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

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

3
Explanation: The path with a sum of 22 is: [5,4,11,2], [5,8,4,5], [4,11,7]
Tips:

Total number of nodes <= 10000

Source: LeetCode
Link: https://leetcode-cn.com/problems/paths-with-sum-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       This question uses double-layer DFS to search, and finally finds the number of all paths that meet the requirements. Please see the code for details.

Three, problem-solving code

class Solution {
public:
    int res = 0;
    int pathSum(TreeNode* root, int sum) {
        if(!root)
            return res;
        dfs(root, sum); //计算以根节点为起点时,所得结果
        pathSum(root->left, sum); //计算以左子节点为起点时,所得结果
        pathSum(root->right, sum);//计算以右子节点为起点时,所得结果
        return res;
    }

    void dfs(TreeNode* root, int sum)
    {
        if(!root)
            return;
        int curNum = root->val;
        if(curNum == sum) res++;
        dfs(root->left, sum-curNum);
        dfs(root->right, sum-curNum);
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108140252