剑指offer-二叉树中和为某一值的路径

时间:2023-01-15 23:12:21

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

解题思路

利用前序遍历的思想,定义FindPath函数,其中paths保存所有符合题目要求的路径,path保存当前遍历到的路径,cNum为当前路径和。从root开始分别在左孩子和右孩子递归的调用FindPath,并更新当前路径path和路径和cNum。若遇到叶子节点,比较当前路径和cNum和期望路径和eNum,若相等则把path加入到paths中。每次遍历完左右孩子时把当前结点值从path中弹出,回溯到父节点开始遍历另一条路径。

代码

 /*
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> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > paths;
vector<int> path;
FindPath(root, expectNumber, paths, path, );
return paths;
}
void FindPath(TreeNode* root,int eNum,vector<vector<int> > &paths,vector<int> &path,int cNum){
if(root != NULL){
path.push_back(root->val);
cNum += root->val;
if(root->left != NULL)
FindPath(root->left, eNum, paths, path, cNum);
if(root->right != NULL)
FindPath(root->right, eNum, paths, path, cNum);
if(root->left == NULL&&root->right == NULL&&cNum == eNum)
paths.push_back(path);
path.pop_back();
}
}
};