【leetcode】【easy】437. Path Sum III

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

題目鏈接:https://leetcode-cn.com/problems/path-sum-iii/

 

思路

本題的sum是從任意位置開始,任意位置結束的。

注意一點:由於樹中有負值元素,路徑可以覆蓋。中途找到解不能直接終止遞歸,因爲可能往下走還能滿足條件。

法一:遞歸

思路一:每次考慮當前節點爲結束節點

時間複雜度O(n),空間複雜度不考慮遞歸是O(logn)。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if(!root) return 0;
        vector<int> rec;
        return path(root, sum, rec);
    }
    int path(TreeNode* root, int sum, vector<int> rec){
        if(!root) return 0;
        int res = 0;
        for(int i=0;i<rec.size();++i){
            rec[i] += root->val;
            if(rec[i]==sum) ++res;
        }
        if(root->val == sum) ++res;
        rec.push_back(root->val);
        return res + path(root->left, sum, rec) + path(root->right, sum, rec);
    }
};

編程筆記:遞歸中傳入引用變量,效果是所有層遞歸函數公用同一個變量,中途被改變,層都能收到;不是引用則只要本函數內被改變,和傳遞給下層的被改變。

思路二:每次考慮當前節點爲開始節點

時間複雜度O(nlgn),空間複雜度不考慮遞歸是O(1)。

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

法二:非遞歸

暫時不寫

發佈了105 篇原創文章 · 獲贊 2 · 訪問量 3225
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章