加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[LeetCode] 113. Path Sum II

发布时间:2020-12-14 04:44:52 所属栏目:大数据 来源:网络整理
导读: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:

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,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,res);
        out.pop_back();
        return;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读