[剑指Offer] 24.二叉树中和为某一值的路径

【思路】

·递归先序遍历树, 把结点加入路径。

·若该结点是叶子结点则比较当前路径和是否等于期待和。

·弹出结点,每一轮递归返回到父结点时,当前路径也应该回退一个结点

注:路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

 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> > res;
13     vector<int> path;
14     void FindDFS(TreeNode* root,int expectNumber) {
15         path.push_back(root->val);
16         //如果是叶子结点则比较当前结点值是否等于期待值
17         if(!root->left && !root->right && root->val == expectNumber)
18         {
19             res.push_back(path);
20         }else{
21             if(root->left)
22                 FindDFS(root->left,expectNumber - root->val);
23             if(root->right)
24                 FindDFS(root->right,expectNumber - root->val);
25         }
26         path.pop_back();
27     }
28     vector<vector<int> > FindPath(TreeNode* root,int expectNumber){
29         if(root != NULL)
30             FindDFS(root,expectNumber);
31         return res;
32     }
33 };

 

posted @ 2017-03-02 15:10  Strawberry丶  阅读(163)  评论(0编辑  收藏  举报