劍指offer---二叉樹中和為某一值的路徑
阿新 • • 發佈:2018-10-31
題目:二叉樹中和為某一值的路徑
要求:輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
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 14 } 15 };
解題程式碼:
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 int currentSum = 0; 16 if(root == NULL) 17 return res; 18search(root, expectNumber, path, res, currentSum); 19 return res; 20 } 21 22 void search(TreeNode* proot, int expectNumber, vector<int> &path, 23 vector<vector<int> > &res, int currentSum){ 24 25 currentSum += proot->val; 26 path.push_back(proot->val); 27 28 bool isLeaf = proot->left == NULL && proot->right == NULL; 29 // 30 if(currentSum == expectNumber && isLeaf){ 31 res.push_back(path); 32 path.pop_back(); 33 return ; 34 } 35 // 36 if(proot->left != NULL) 37 search(proot->left, expectNumber, path, res, currentSum); 38 if(proot->right != NULL) 39 search(proot->right, expectNumber, path, res, currentSum); 40 path.pop_back(); 41 } 42 };
時間有限,先把答案放到這裡,有時間再過來新增詳細內容。