题目描述
|
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
|
题目分析
|
遍历二叉树的每个节点,每遍历一个节点,将节点压入路径中,当该节点为叶子节点时,判断路径上的节点和是否为给定值,如果是则保存路径,否则将节点值从路径中弹出,继续遍历下一个节点。
|
代码实现
class Solution {
public:
vector<vector<int>>routs;
vector<int>rout;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root == NULL) return routs;
rout.push_back(root->val);
if(root->left == NULL && root->right == NULL)
if(root->val == expectNumber)
routs.push_back(rout);
if(root->left) FindPath(root->left, expectNumber-root->val);
if(root->right) FindPath(root->right, expectNumber-root->val);
rout.pop_back();
return routs;
}
};