【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。

这里为了练习递归思想,暂时不实现非递归方法了,后序可能会再补上。

发布了126 篇原创文章 · 获赞 2 · 访问量 3740

猜你喜欢

转载自blog.csdn.net/lemonade13/article/details/104408568