题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:
先序遍历整个二叉树,找出二叉树中结点值的和为输入整数的所有路径。
样例
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int>> res; //存储所有路径
vector<int> path; //存储当前路径
void dfs(TreeNode* root, int sum)
{
if(!root) return;
path.push_back(root->val);
sum = sum-root->val;
if(sum < 0) return;
//sum == 0 且找到了叶节点 确定一条路径
if(sum==0 && !root->left && !root->right) res.push_back(path);
dfs(root->left, sum);
dfs(root->right, sum);
//Removes the last element in the vector,
//effectively reducing the container size by one.
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root,int sum) {
dfs(root, sum);
return res;
}
};