leetcode 437. Path Sum III

方法一:

直接dfs。

    int pathSum(TreeNode* root, int sum) {
        if (root == NULL)
            return 0;
        return dfs(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
    }
    
    int dfs(TreeNode* root, const int& sum) {
        if (root == NULL)
            return 0;
        int ret = 0;
        if (root->val == sum)
            ret++;
        ret += dfs(root->left, sum - root->val);
        ret += dfs(root->right, sum - root->val);
        return ret;
    }

方法二:

用哈希保存从根节点到当前节点的和,减去sum,看是否在哈希中出现过,出现过则加上。

    int help(TreeNode* root, int sum, unordered_map<int, int>& store, int pre) {
        if (!root) return 0;
        root->val += pre;
        int res = (root->val == sum) + (store.count(root->val - sum) ? store[root->val - sum] : 0); // 总和等于sum,或曾经出现过
        store[root->val]++;
        res += help(root->left, sum, store, root->val) + help(root->right, sum, store, root->val);
        store[root->val]--;
        return res;
    }

    int pathSum(TreeNode* root, int sum) {
        unordered_map<int, int> store;
        return help(root, sum, store, 0);
    }

 

posted on 2018-02-27 11:48  willaty  阅读(133)  评论(0编辑  收藏  举报

导航