1. 程式人生 > >數據結構之二叉樹(二)

數據結構之二叉樹(二)

創建 int iter out for 結點 spa left nbsp

輸出二叉樹中所有從根結點到葉子結點的路徑

 1 #include <iostream>  
 2 #include <vector>  
 3 using namespace std;  
 4 
 5 struct BiTNode  
 6 {  
 7     char m_value;  
 8     BiTNode *m_left;  
 9     BiTNode *m_right;  
10 };  
11 
12 //先序創建二叉樹  
13 void CreatBiTree(BiTNode *&root)  
14 { 15 char nValue = 0; 16 cin >> nValue; 17 if (# == nValue) 18 { 19 return; 20 } 21 else 22 { 23 root = new BiTNode(); 24 root->m_value = nValue; 25 CreatBiTree(root->m_left); 26 CreatBiTree(root->m_right);
27 } 28 } 29 30 //輸出二叉樹中所有從根結點到葉子結點的路徑(遞歸) 31 void FindAllPath(BiTNode *pRoot, vector<char> path) 32 { 33 if (pRoot != NULL) 34 { 35 path.push_back(pRoot->m_value); 36 if (pRoot->m_left == NULL && pRoot->m_right == NULL)
37 { 38 for (vector<char>::iterator iter=path.begin(); iter!=path.end(); iter++) 39 { 40 cout << *iter << " "; 41 } 42 cout << endl; 43 return; 44 } 45 else 46 { 47 FindAllPath(pRoot->m_left, path); 48 FindAllPath(pRoot->m_right, path); 49 } 50 } 51 } 52 53 int main() 54 { 55 BiTNode *pRoot = NULL; 56 vector<char> path; 57 CreatBiTree(pRoot); 58 cout << "二叉樹中從根到葉子結點的所有路徑如下:" << endl; 59 FindAllPath(pRoot, path); 60 system("pause"); 61 return 0; 62 }

數據結構之二叉樹(二)