一.题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
二.代码(C++)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
private:
vector<vector<int> > out;
vector<int> tmp;
void dsf(TreeNode* root,int num)
{
if(!root)
return;
tmp.push_back(root->val);
if(num == root->val && !root->left && !root->right)
out.push_back(tmp);
dsf(root->left,num-root->val);
dsf(root->right,num-root->val);
tmp.pop_back();
}
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(!root)
return out;
dsf(root,expectNumber);
return out;
}
};
三.提交记录
四.备注
遍历所有路径,找到符合要求的路径。注意每次迭代时对数组的操作。