返回

[Leetcode]437. Path Sum III(C++)

题目描述

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

例子

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. The paths that sum to 8 are:

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

解题思路

方法一

可以用一个变量来维护从 root 到当前节点的和,再递归的以所有节点为 root 进行遍历,代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if (root == nullptr) return 0;
        return pathSumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
    }

private:
    int pathSumUp(TreeNode* node, int current_sum, int target_sum) {
        if (node == nullptr) return 0;
        current_sum += node->val;
        return (current_sum == target_sum) + pathSumUp(node->left, current_sum, target_sum) + pathSumUp(node->right, current_sum, target_sum);
    }

};
  • 时间复杂度: O(n^2)
  • 空间复杂度: O(n)

方法二

第一种方法本质上可以转换成判断两条路径,一个是从 root 到 节点 i, 一条是从 root 到节点 j (必须要经过 i),计算这两条路径的和(前缀和 prefix)并相减就可以知道从 ij 的和;根据这个思路,如果我们只用一次遍历树,并记录从 root 到当前节点 i 的和,那么问题就转换成,在 j 之前有多少个节点 i 满足 prefix(i) = prefix(j) - target,根据这个思路,我们可以用一个哈希表来存储所有节点的 prefix,这样就不需要递归遍历,注意一下当遍历完当前子树的时候应该将当前子树的所有 prefix 从哈希表删掉,不然会影响其他子树的结果,代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        ans = 0;
        prefix_sum_count[0] = 1;

        dfs(root, 0, sum);
        return ans;
    }

private:
    std::unordered_map<int, int> prefix_sum_count;
    int ans;

    void dfs(TreeNode* node, int current_sum, int target_sum) {
        if (node == nullptr) return;
        current_sum += node->val;
        ans += prefix_sum_count[current_sum - target_sum];
        prefix_sum_count[current_sum]++;
        dfs(node->left, current_sum, target_sum);
        dfs(node->right, current_sum, target_sum);
        // key step!
        prefix_sum_count[current_sum]--;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(h) -> 只跟树的最大高度有关,因为哈希表不会同时存放左右两个子树的值
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy