这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » path-sum-ii

共1条 1/1 1 跳转至

path-sum-ii

高工
2018-01-23 12:20:02     打赏

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 andsum = 22,

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

return

[
   [5,4,11,2],
   [5,8,4,5]
]
[cpp] view plain copy
  1. class Solution {  

  2. public:  

  3.     vector<vector<int>> pathSum(TreeNode* root, int sum)  

  4.     {  

  5.         vector<vector<int>> ret;  

  6.         vector<int> tmp;  

  7.         pathSumone(root, sum, ret, tmp);  

  8.     }  

  9.     void pathSumone(TreeNode* root, int sum, vector<vector<int>>& vv, vector<int> tmp)  

  10.     {  

  11.         if (root==NULL)  

  12.         {  

  13.             return;  

  14.         }  

  15.   

  16.         tmp.push_back(root->val);  

  17.         if (root->left==NULL && root->right==NULL && sum-root->val==0)  

  18.         {  

  19.             vv.push_back(tmp);  

  20.         }  

  21.         pathSumone(root->left, sum-root->val, vv, tmp);  

  22.         pathSumone(root->right, sum-root->val, vv, tmp);  

  23.     }  

  24. };  





题意:返回所有路径和为sum的所有路径;




共1条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]