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

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
 
 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 private:
12     void FindPath(TreeNode* root, int expectNumber, int currentSum, vector<vector<int> > &res, vector<int> &path) {
13         currentSum += root->val;
14         path.push_back(root->val);
15         bool isLeaf = root->left == NULL && root->right == NULL;
16         if (currentSum == expectNumber && isLeaf) {
17             res.push_back(path);
18         }
19         if (root->left != NULL)
20             FindPath(root->left, expectNumber, currentSum, res, path);
21         if (root->right != NULL)
22             FindPath(root->right, expectNumber, currentSum, res, path);
23         path.pop_back();
24     }
25 public:
26     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
27         vector<vector<int> > res;
28         vector<int> path;
29         if (root == NULL)
30             return res;
31         int currentSum = 0;
32         FindPath(root, expectNumber, currentSum, res, path);
33         return res;
34     }
35 };

 

 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> > res;
14         vector<int> path;
15         if (root) {
16             dfs(root, res, path, expectNumber);
17         }
18         return res;
19     }
20     void dfs(TreeNode *root, vector<vector<int> > &res, vector<int> &path, int s) {
21         path.push_back(root->val);
22         if (!root->left && !root->right) {
23             if (s == root->val) {
24                 res.push_back(path);
25             }
26         }
27         if (root->left) {
28             dfs(root->left, res, path, s - root->val);
29         }
30         if (root->right) {
31             dfs(root->right, res, path, s - root->val);
32         }
33         path.pop_back();
34     }
35 };

note that: 代码没有实现括号内的功能

 
 
posted @ 2019-08-12 14:45  琴影  阅读(397)  评论(0编辑  收藏  举报