LeetCode 437. 路徑總和 III (起點、終點都不唯一的路徑數目)

路徑總和 III
此題和 112路徑和 的區別點在於起點和終點都不確定,難點也在於此。

  • 終點不確定如何解決?
    遍歷一整棵子樹,搜索過程中只要路徑和滿足要求,答案加1
  • 起點不確定如何解決?
    既然起點不確定,那就分別每個節點作爲搜索的起點
    所以實際上這個題目由兩重遞歸組成,對二叉樹中的每個節點都作爲搜索起點,求路徑和。

時間複雜度:O(n2)O(n^2)

/**
 * 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 helper(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
    }
    int helper(TreeNode *root,int sum){
        if(!root) return 0;
        sum -= root->val;
        return !sum+helper(root->left,sum)+helper(root->right,sum);
    }
};

另一種風格,不返回值,參數帶一個引用。

/**
 * 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;
        }
        int res = 0 ;
        helper(root,sum,res);
        return res+pathSum(root->left,sum)+pathSum(root->right,sum);
    }
    void helper(TreeNode* root,int sum,int &res){
        if(!root){
            return;
        }
        if(sum==root->val){
            res++;
        }
        if(root->left){
            helper(root->left,sum-root->val,res);
        }
        if(root->right){
            helper(root->right,sum-root->val,res);
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章