设为首页 加入收藏

TOP

LeetCode[Tree]: Path Sum II
2015-07-20 17:21:06 来源: 作者: 【 】 浏览:3
Tags:LeetCode Tree Path Sum

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,

\

return

\

这个题目适合用递归来解,我的C++代码实现如下:

class Solution {
public:
    vector
   
     > pathSum(TreeNode *root, int sum) { vector
    
      > paths; vector
     
       curr_path; if (!root) return paths; find(root, sum, paths, curr_path); return paths; } private: void find(TreeNode *root, int sum, vector
      
        > &paths, vector
       
         &curr_path) { curr_path.push_back(root->val); if (root->left == nullptr && root->right == nullptr) if (root->val == sum) paths.push_back(curr_path); if (root->left) { find(root->left, sum - root->val, paths, curr_path); curr_path.pop_back(); } if (root->right) { find(root->right, sum - root->val, paths, curr_path); curr_path.pop_back(); } } };
       
      
     
    
   

时间性能如下图所示:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ1717 Dominoes DP,背包的变形 下一篇BZOJ 1076 SCOI2008 奖励关 期望..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)