Shirlies
宁静专注认真的程序媛~

题目:

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

链接:

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:

从根节点开始计算路径上节点和,直到叶子节点,如果此时的和与期望值相同,则输出到ans中;

这里在类中使用了一个成员来记录路径,每次访问子节点时,将该节点记录下来,退栈时将该节点pop掉即可。

代码:

 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     vector<vector<int> > ans;
13     vector<int> tmpVec;
14     
15     void visitTree(TreeNode *root,int sumNum,int expectNum){
16         TreeNode *left = root->left;
17         TreeNode *right = root->right;
18         if(left == NULL && right == NULL){
19             if(sumNum == expectNum){
20                  this->ans.push_back(this->tmpVec);
21             }
22             return;
23         }
24         
25         if(left != NULL){
26             this->tmpVec.push_back(left->val);
27             this->visitTree(left,sumNum + left->val,expectNum);
28             this->tmpVec.pop_back();
29         }
30         
31         if(right != NULL){
32             this->tmpVec.push_back(right->val);
33             this->visitTree(right,sumNum + right->val,expectNum);
34             this->tmpVec.pop_back();
35         }
36         
37         return;
38     }
39 public:
40     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
41         this->ans.clear();
42         this->tmpVec.clear();
43         
44         if(root != NULL){
45             this->tmpVec.push_back(root->val);
46             this->visitTree(root,root->val,expectNumber);
47         }
48         
49         return this->ans;
50     }
51 };

 

posted on 2016-09-03 09:56  Shirlies  阅读(319)  评论(0)    收藏  举报