二叉树根节点到叶子节点路径和为指定值的所有路径
二叉树根节点到叶子节点和为指定值的路径
http://www.nowcoder.com/questionTerminal/840dd2dc4fbd4b2199cd48f2dadf930a
先序遍历,套模版就是了,没啥可解释的。
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector<vector<int>> res;
if (!root) return res;
vector<int> path;
preOrder(root, res, path, sum, 0);
return res;
}
void preOrder(TreeNode* root, vector<vector<int> > &res, vector<int> path, int sum, int current) {
if (!root) return;
current = current + root->val;
path.push_back(root->val);
if (!root->left && !root->right && sum == current) res.push_back(path);
if (root->left) preOrder(root->left, res, path, sum ,current);
if (root->right) preOrder(root->right, res, path, sum ,current);
}
};刷遍天下无敌手 文章被收录于专栏
秋招刷题历程

