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

题目描述

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

解题思路

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

代码

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
13         vector<vector<int> > paths;
14         vector<int> path;
15         FindPath(root, expectNumber, paths, path, 0);
16         return paths;
17     }
18     void FindPath(TreeNode* root,int eNum,vector<vector<int> > &paths,vector<int> &path,int cNum){
19         if(root != NULL){
20             path.push_back(root->val);
21             cNum += root->val;
22             if(root->left != NULL)
23                 FindPath(root->left, eNum, paths, path, cNum);
24             if(root->right != NULL)
25                 FindPath(root->right, eNum, paths, path, cNum);
26             if(root->left == NULL&&root->right == NULL&&cNum == eNum)
27                 paths.push_back(path);
28             path.pop_back();
29         }
30     }
31 };
原文地址:https://www.cnblogs.com/wmx24/p/8707479.html