113. Path Sum II

15 篇文章 0 订阅

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

For 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]
]

【问题分析】

  这个问题和Path Sum类似,提高了一些要求:

  1、结束条件不同,找到满足条件的路径后不能直接结束,需要继续寻找可能满足条件的路径
  2、要求把找到的路径保存下来

【AC代码】

  

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
            std::vector<int> path;
            std::vector<std::vector<int> > paths;
            if (root == NULL) {                      //返回所有结果路径集合
                //paths.push_back(path);
               //the key point
               return paths; 
            }
            if (root->left == NULL && root->right == NULL) {    //遇到叶子节点,获取当前路径,并加入结果路径集合中
                if (root->val == sum) {
                    path.push_back(sum);
                    paths.push_back(path);
                }
                return paths;
            }

            if (root->left != NULL) {
                std::vector<std::vector<int> > lpaths = pathSum(root->left, sum - root->val);    //获取左子节点的所有路径
                for (int i = 0; i < lpaths.size(); ++i) {                                        //将当前节点插入到每条路径的起始位置
                    lpaths[i].insert(lpaths[i].begin(), root->val);
                    paths.push_back(lpaths[i]);
                }

            }
            if (root->right != NULL) {
                std::vector<std::vector<int> > rpaths = pathSum(root->right, sum - root->val);    //获取右子节点的所有路径
                for (int i = 0; i < rpaths.size(); ++i) {
                    rpaths[i].insert(rpaths[i].begin(), root->val);                               //将当前节点插入到每条路径的起始位置
                    paths.push_back(rpaths[i]);
                }
            }
            return paths;
        }

};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值