1. 程式人生 > >劍指Offer——二叉樹中和為某一值的路徑

劍指Offer——二叉樹中和為某一值的路徑

roo int paths struct () node nod cnblogs ret

題目描述:

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。


分析:

先序遍歷二叉樹,找到二叉樹中結點值的和為輸入整數的路徑,加入到路徑數組中。

註意:路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。必須到達葉子結點。

這個問題是可以深度優先搜索,也可以廣度優先搜索。


深度優先搜索代碼:

 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 if(root == NULL) return paths; 14 vector<int> path; 15 MyFindPath(root, expectNumber, path);
16 return paths; 17 } 18 void MyFindPath(TreeNode* root, int expectNumber, vector<int> &path) { // 先序遍歷 19 if(root == NULL) return; 20 path.push_back(root->val); 21 if(expectNumber == root->val && root->left == NULL && root->right == NULL) {
22 paths.push_back(path); // 存在expectNumber等於root->val,加入結果數組中 23 } 24 MyFindPath(root->left, expectNumber - root->val, path); 25 MyFindPath(root->right, expectNumber - root->val, path); 26 path.pop_back(); 27 } 28 private: 29 vector<vector<int> > paths; 30 };

劍指Offer——二叉樹中和為某一值的路徑