[LeetCode] 113、路徑總和 II

題目描述

給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。

示例:
給定如下二叉樹,以及目標和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

解題思路

《劍指offer》第34題,基於樹的前序遍歷。

參考代碼

// 基於樹的前序遍歷(“回溯”)
class Solution {
public:
    vector<vector<int> > pathSum(TreeNode* root, int expectNumber) {
        if(root == nullptr)
            return res;
            
        vector<int> path;  // 用vector實現“棧”
        int currentSum = 0;
        getPathRecursively(root, expectNumber, path, currentSum);
        
        return res;
    }
    
    void getPathRecursively(TreeNode* root, int expectNumber, vector<int> &path, int currentSum){
        if(root != nullptr){
            currentSum += root->val;
            path.push_back(root->val);
            
            bool isLeaf = root->left == nullptr && root->right == nullptr;
            if(isLeaf && currentSum == expectNumber){
                res.push_back(path);
            }
            
            if(root->left){
                getPathRecursively(root->left, expectNumber, path, currentSum);
            }
            if(root->right){
                getPathRecursively(root->right, expectNumber, path, currentSum);
            }
            
            currentSum -= root->val;  // 若currentSum傳的不是引用,這行不加也行。(最好還是加上,更能體現“回溯”)
            path.pop_back();
        }
        
    }

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