1. 程式人生 > 實用技巧 >劍指office--------二叉樹中和為某一值的路徑

劍指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 };