Golden interview programmers - face questions 04.12 summation path (recursive binary tree)

1. Topic

Given a binary tree, where each node contains an integer value (this value is either positive or negative).

Design an algorithm, a value equal to the sum of the number of all nodes print paths given value.

Note that the path does not have to start or end from the binary tree root or leaf nodes, but it must be downward direction (the direction can only point to a child node from the parent node).

示例:
给定如下二叉树,以及目标和 sum = 225
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

3
解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7]

提示:
节点总数 <= 10000

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/paths-with-sum-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • Traversing each node, and the node and the counted
class Solution {
    int count = 0;
public:
    int pathSum(TreeNode* root, int sum) {
        if(!root) return 0;
        calsum(root,0,sum);
        pathSum(root->left,sum);
        pathSum(root->right,sum);
        return count;
    }

    void calsum(TreeNode* root, int s, int sum)
    {
        if(!root)  
            return;
        if(s+root->val == sum)
            count++;
        calsum(root->left,s+root->val,sum);
        calsum(root->right,s+root->val,sum);
    }
};

Here Insert Picture Description

Published 763 original articles · won praise 985 · views 280 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105085793