1. 程式人生 > >24、劍指offer--二叉樹中和為某一值的路徑

24、劍指offer--二叉樹中和為某一值的路徑

val 遍歷 描述 所有 oid res bold eno bsp

題目描述 輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。 解題思路:本題采用先序遍歷,遍歷到葉子節點,如果和不等於其值,則返回至上一層的根結點,本題使用棧結構來存儲路徑,這樣可以方便返回上一父結點的時候,將當前結點從路徑中刪除
 1 /*struct TreeNode {
 2     int val;
 3     struct TreeNode *left;
 4     struct TreeNode *right;
 5     TreeNode(int x) :
 6             val(x), left(NULL), right(NULL) {
7 } 8 };*/ 9 class Solution { 10 public: 11 vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { 12 vector<int> tmp; 13 vector<vector<int> >result; 14 if(root == NULL || expectNumber<=0) 15 return result; 16 IsPath(root,expectNumber,result,tmp);
17 return result; 18 } 19 void IsPath(TreeNode* root,int expectNumber,vector<vector<int> > &findPath,vector<int> &path)//不是取地址的話,結果不正確 20 { 21 path.push_back(root->val); 22 if(root == NULL) 23 return; 24 bool isLeaf = (root->left == NULL)&&(root->right == NULL);
25 if((root->val == expectNumber)&&isLeaf) 26 { 27 findPath.push_back(path); 28 } 29 else 30 { 31 if(root->left != NULL) IsPath(root->left,expectNumber-root->val,findPath,path); 32 if(root->right != NULL) IsPath(root->right,expectNumber-root->val,findPath,path); 33 } 34 path.pop_back(); 35 } 36 };
備註:vector<vector<int> > r接收返回值,其輸出應該為
 1 vector<vector<int> > r;
 2 r = s.FindPath(T1,n);
 3      
 4 for(int i=0;i<r.size();i++)
 5 {
 6     for(int j=0;j<r[i].size();j++)
 7     {
 8         cout<<r[i][j]<<" ";
 9     }
10     cout<<endl;
11 }

24、劍指offer--二叉樹中和為某一值的路徑