LeetCode(113) Path Sum II
2015-10-20 12:54
393 查看
题目
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,
分析
本题目与上一题 LeetCode(112) Path Sum虽然类型相同,但是需要在以前的基础上,多做处理一些:与Path Sum相比,本题是求出路径,所以,在找到满足的路径之后,不能直接返回,而是将其添加到一个vector < vector >中。在查找的过程中,每经过一个结点,先使用一个vector将该路径中的所有结点记录下来。由于vector< vector>是用来记录所有满足的路径的,所以传递引用给它是为了对它的每一个改动都是对其本身的操作,而不是对其副本的操作,使用来返回找到的所有路径。使用的vector只是拷贝操作,所以都是对其副本的操作,不会对原始的vector有影响。
AC代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { if (!root) return vector<vector<int>>(); //存储所有满足条件的路径 vector<vector<int> > paths; //存储当前遍历路径 vector<int> tmp; getPaths(root, sum, paths, tmp); return paths; } void getPaths(TreeNode *root, int sum, vector<vector<int> > &paths, vector<int> tmp) { if (!root) return; tmp.push_back(root->val); if (!root->left && !root->right && sum == root->val) paths.push_back(tmp); if (root->left) getPaths(root->left, sum - root->val, paths, tmp); if (root->right) getPaths(root->right, sum - root->val, paths, tmp); } };
GitHub测试程序源码
相关文章推荐
- python在linux(anaconda)的图形界面(snack)
- 【AD系列教程】在PCB中加入任意图形
- 加法器(减法器)运算放大电路
- select option
- Python复制目录结构脚本代码分享(转)
- 到底snappy ubuntu core是什么?
- 成大事必须依靠的五种人和十种手段!
- 小心API 21上的EditText
- OPENCV笔记之环境搭建
- jQuery unbind 删除绑定事件 / 移除标签方法
- MAC 下安装、配置MySql 及 MySql、Openfire卸载
- Android中的Selector的用法
- 新的AppBarLayout flag:SCROLL_FLAG_SNAP
- 阿里云常用压缩和ngnix命令
- docker for windows 安装
- [MFC]ToolBar添加新图标无法显示的问题
- JS-----元素定位自动居中
- 典型关联分析
- tableView不执行didselsct代理方法
- [系统]对EFI分区以及UEFI,GPT,BIOS,MBR启动的理解