[LeetCode] 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]
]

题目要求将二叉树中结点数值加和等于sum的路径列出。
和上一道题类似,上一道题只要二叉树中存在加和等于sum的一支就可。这道题在加和方面和上一道题思路一样,使用递归的方法计算根结点到一个叶子节点路径上的结点值加和。
不同的是要对记录路径结点的数组out进行回退。无论到叶子结点时加和是否等于sum都要对out进行回退,然后判断上个结点的另一子树是否可以满足要求。


具体代码如下:
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> out;
        path(root,sum,out,res);
        return res;
    }
    void path(TreeNode* root,int sum,vector<int> &out,vector<vector<int>> &res){
        if(!root){
            res={};
            return; 
        }
        out.push_back(root->val);
        if(!root->left && !root->right && root->val==sum) {
            res.push_back(out);
        }
        if(root->left)path(root->left,sum-root->val,out,res);
        if(root->right)path(root->right,sum-root->val,out,res);
        out.pop_back();
        return;
    }
};

猜你喜欢

转载自www.cnblogs.com/cff2121/p/10988120.html