LeetCode 437 Path Sum III

題目:

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.

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

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11
題目鏈接

題意:

給一棵二叉樹,其中每個節點包含一個整數值。給定一個值sum,要求找到路徑和爲sum的路徑的個數。

路徑不需要從root開始或結束,但必須向下(只能從父節點到子節點)

數的節點數不超過1000個,取值範圍在-1000000到1000000之間。

由於路徑並不要求必須以葉子爲終點,所以不能寫從葉子向上遞加的算法,通過觀察得出,每一個非葉子結點都可以作爲一段路徑的起點,而每一個非根節點結點都可以作爲一段路經的終點,所以我們可以遍歷整個樹,枚舉所有可能的起點,對與每一個起點進行搜索,以其開始的路徑是否有長度爲sum的,有的話,ans++,當所有遍歷結束,返回ans。

代碼如下:

class Solution {
public:
    int target, ans = 0;
    void upToSum(TreeNode* node, int sum) {
        if (!node) return;
        sum += node->val;
        if (sum == target) {
            ans++;
        }
        upToSum(node->left, sum);
        upToSum(node->right, sum);
    }
    void dfs(TreeNode * node) {
        if (!node) return;
        upToSum(node, 0);
        dfs(node->left);
        dfs(node->right);
    }
    int pathSum(TreeNode* root, int sum) {
        target = sum;
        dfs(root);
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章