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

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

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

 

 

Code:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void findPath(TreeNode *node, int n, int &sum, vector
&buf, vector
> &res){ if(!node) return; buf.push_back(node->val); if(!node->left&&!node->right&&node->val+n==sum){ res.push_back(buf); buf.pop_back(); return; } findPath(node->left,node->val+n,sum,buf,res); findPath(node->right,node->val+n,sum,buf,res); buf.pop_back(); } vector
> pathSum(TreeNode *root, int sum) { vector
buf; vector
> res; findPath(root,0,sum,buf,res); return res; }};

  

转载于:https://www.cnblogs.com/winscoder/p/3535398.html

你可能感兴趣的文章
UVa 825 - Walking on the Safe Side
查看>>
Could not load file or assembly or one of its dependencies. 试图加载格式不正确的程序。
查看>>
PHP超大文件下载,断点续传下载
查看>>
C++ overloading contructor
查看>>
怎样配置PHP环境和安装Zendstdio编辑器
查看>>
基于Maven构建开发第一个Storm项目
查看>>
SQL Server on Linux 理由浅析
查看>>
Oracle database
查看>>
JAVA - JAVA编译运行过程
查看>>
Android 手势识别类 ( 三 ) GestureDetector 源码浅析
查看>>
numpy.percentile
查看>>
[maven] 使用Nexus创建maven私有仓库
查看>>
Linux下安装JDK
查看>>
java设计模式之策略
查看>>
解决Centos关闭You have new mail in /var/spool/mail/root提示
查看>>
手把手教你反编译别人的APP
查看>>
MapReduce的集群行为和框架
查看>>
Oracle表变化趋势追踪记录
查看>>
排序算法总结之希尔排序
查看>>
python中set使用
查看>>