题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路
首先想到的自然是递归。递归思路为,若当前节点为空,则返回;若当前节点为叶子节点,且val与期望数值相等,则将该路径加入结果;若当前节点为非叶节点,则期望数值减去该节点的val,然后递归调用左右子树。
困难的地方不在于递归,而在于记录多条路径。一种讨巧的方式是用全局变量或者成员变量。
class Solution {
public:
vector<int> path;
vector<vector<int> > res;
void findPath(int num,TreeNode* node){
if(node==NULL) return ;
path.push_back(node->val);
//叶子节点
if(node->left==NULL && node->right==NULL){
if(num == node->val) {
res.push_back(path);
}
}
findPath(num-node->val,node->left);
findPath(num-node->val,node->right);
path.erase(path.end()-1);//路径要记得清理已走过的节点
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL) return res;
findPath(expectNumber,root);
return res;
}
};
另外一种方法则是通过参数引用传递路径向量。
class Solution {
public:
void findPath(int num,TreeNode* node,vector<vector<int> >& res,vector<int>& path){
if(node==NULL) return ;
path.push_back(node->val);
//叶子节点
if(node->left==NULL && node->right==NULL){
if(num == node->val) {
res.push_back(path);
}
}
findPath(num-node->val,node->left,res,path);
findPath(num-node->val,node->right,res,path);
path.erase(path.end()-1);//路径要记得清理已走过的节点
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<int> path;
vector<vector<int> > res;
if(root==NULL) return res;
findPath(expectNumber,root,res,path);
return res;
}
};
个人觉得还是第二个方法比较好,虽然函数参数个数多了一点。