博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Path Sum II
阅读量:4562 次
发布时间:2019-06-08

本文共 1571 字,大约阅读时间需要 5 分钟。

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]]
1 /**  2  * Definition for binary tree  3  * struct TreeNode {  4  *     int val;  5  *     TreeNode *left;  6  *     TreeNode *right;  7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  8  * };  9  */  10 class Solution {  11 public:  12     vector
> pathSum(TreeNode *root, int sum) { 13 14 vector
> gather; 15 vector
rootLeaf; 16 int tempSum = 0; 17 pathSum(root, tempSum, sum, gather, rootLeaf); 18 return gather; 19 } 20 21 void pathSum(TreeNode *root, int tempSum, int sum, vector
> &gather, vector
rootLeaf) 22 { 23 if(root != NULL) 24 { 25 if(root->left == NULL && root->right == NULL) 26 { 27 tempSum += root->val; 28 rootLeaf.push_back(root->val); 29 if(tempSum == sum) 30 gather.push_back(rootLeaf); 31 32 return; 33 } 34 35 else 36 { 37 tempSum += root->val; 38 rootLeaf.push_back(root->val); 39 pathSum(root->left, tempSum, sum, gather, rootLeaf); 40 pathSum(root->right, tempSum, sum, gather, rootLeaf); 41 } 42 } 43 } 44 };

 

转载于:https://www.cnblogs.com/YQCblog/p/3970189.html

你可能感兴趣的文章
Paint Chain HDU - 3980(sg)
查看>>
Chales常用操作
查看>>
C++ 运算符重载<<
查看>>
windows镜像
查看>>
Flask 模板语法
查看>>
spark-2.2.0安装和部署——Spark集群学习日记
查看>>
ZOJ FatMouse' Trade 贪心
查看>>
音乐播放器
查看>>
SQL COOKBOOK (Ch.1-10)
查看>>
创建数组
查看>>
dict使用
查看>>
[转] 移动平台Html5的viewport使用经验
查看>>
ASP.NET MVC的帮助类HtmlHelper和UrlHelper
查看>>
《Python数据科学手册》第五章机器学习的笔记
查看>>
ubuntu16.04 配置爬虫环境
查看>>
Centos7,PHP7安装swoole
查看>>
02_ListActive中响应事件 并LogCat输出
查看>>
doubleclick adx note
查看>>
Celery框架
查看>>
[c#]asp.net开发微信公众平台(4)关注事件、用户记录、回复文本消息
查看>>