【leetcode】【medium】113. Path Sum II

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

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

Return:

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

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

 

思路

法一:遞歸

treePathpathSum兩道題的思路綜合,能理解前兩題的思路,就很容易得到本題思路。

/**
 * 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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if(!root) return res;
        if(!root->left && !root->right){
            if (sum == root->val){
                vector<int> tmp = {root->val};
                res.push_back(tmp);
            }
            return res;
        }
        vector<vector<int>> l = pathSum(root->left, sum-root->val);
        for(auto item: l){
            item.insert(item.begin(), root->val);
            res.push_back(item);
        }
        vector<vector<int>> r = pathSum(root->right, sum-root->val);
        for(auto item: r){
            item.insert(item.begin(), root->val);
            res.push_back(item);
        }
        return res;
    }
};

法二:非遞歸

非遞歸的實現方法有很多:

1)用queue/stack實現的前/中/後/層序遍歷。

2)用前驅後繼節點實現的DFS。

這裏爲了練習遞歸思想,暫時不實現非遞歸方法了,後序可能會再補上。

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