leetcode_c++:树: Path SumII(113)
2016-08-25 16:48
316 查看
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
O(n)
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] ]
算法
dfsO(n)
class Solution { private: void dfs(TreeNode *root, int rest, vector<int> &path, vector<vector<int> > &res) { if (root == NULL) return; path.push_back(root->val); rest -= root->val; if (root->left == NULL && root->right == NULL) { if (rest == 0) res.push_back(path); } else { if (root->left) dfs(root->left, rest, path, res); if (root->right) dfs(root->right, rest, path, res); } path.pop_back(); } public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > res; vector<int> path; dfs(root, sum, path, res); return res; } };
相关文章推荐
- HDU 4907 Task schedule(二分算法)
- C++学习笔记(一) 补充篇 基础语法 — 参考慕课网 值得推荐!
- c++之const限定符
- c++中.dll与.lib文件的生成
- POJ 1835 宇航员
- leetcode_c++:树: Path Sum(112)
- leetcode_c++:树: Minimum Depth of Binary Tree(111)
- poj-1611The Suspects(并查集求被感染的人数)
- leetcode_c++:树:Balanced Binary Tree(110)
- C/C++复习(4):运算符
- C++ 类相关
- C++ 单例模式 出现错误“: 无法解析的外部符号”
- 字符串替换函数strreplace
- leetcode_c++:树:Convert Sorted Array to Binary Search Tree(108)
- C#调用C++、Opencv的Dll
- c++大数模板类
- C/C++复习(3):数据类型
- leetcode_c++:树: Binary Tree Level Order Traversal II (107)
- C语言(Bug) warning: this program uses gets(), which is unsafe.
- C++多线程和任务等待问题