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

题目描述

输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 
 
 
 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     void Cal(TreeNode* root,vector<int> way,vector<vector<int> > &ans,int expectNumber,int sum){
13         way.push_back(root->val);
14         if (root->left==NULL&&root->right==NULL){
15             if (sum==expectNumber){
16 //                way.push_back(root->val);
17                 ans.push_back(way);
18                 return ;
19             }
20             return ;
21         }
22 //        if (sum>expectNumber)    return ;
23         if (root->left!=NULL){
24            
25             Cal(root->left,way,ans,expectNumber,sum+root->left->val);
26         }
27         if (root->right!=NULL){
28             
29             Cal(root->right,way,ans,expectNumber,sum+root->right->val);
30         }
31         return ;
32     }
33     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
34         
35         vector<vector<int> > ans;
36         if (root==NULL)    return ans;
37         vector<int> way;
38         
39         Cal(root,way,ans,expectNumber,root->val);
40         return ans;
41     }
42 };
原文地址:https://www.cnblogs.com/q1204675546/p/13362559.html