Leetcode之 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

代碼:

方法一——自己的方法,沒有通過,是錯的:

int helper(TreeNode* root, int sum, bool b) {
    if (!root)return 0;
    //if (!b && (!root->left) && (!root->right))return 0;
    if (b&&root->val == sum) {
        return 1;
    }
    if (b) {
        return helper(root->left, sum - root->val, true) + helper(root->right, sum - root->val, true);
    }
    else {
        return helper(root->left, sum, true) + helper(root->left, sum, false) + helper(root->right, sum, true) + helper(root->right, sum, false);
    }
}

int pathSum(TreeNode* root, int sum) {
    if (!root)return 0;
    if (root->val == sum)return 1;
    return helper(root, sum, false) + helper(root, sum, true);
}

方法二——先序遍歷,記錄路徑的方法:

class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        int res = 0;
        vector<TreeNode*> out;
        helper(root, sum, 0, out, res);
        return res;
    }
    void helper(TreeNode* node, int sum, int curSum, vector<TreeNode*>& out, int& res) {
        if (!node) return;
        curSum += node->val;
        out.push_back(node);
        if (curSum == sum) ++res;
        int t = curSum;
        for (int i = 0; i < out.size() - 1; ++i) {
            t -= out[i]->val;
            if (t == sum) ++res;
        }
        helper(node->left, sum, curSum, out, res);
        helper(node->right, sum, curSum, out, res);
        out.pop_back();
    }
};

方法三——採用兩個遞歸,思路清晰,又簡單

class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if (!root) return 0;
        return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
    }
    int sumUp(TreeNode* node, int pre, int& sum) {
        if (!node) return 0;
        int cur = pre + node->val;
        return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
    }
};

 

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