输出二叉树中所有从根结点到叶子结点的路径
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 }
时间: 2024-10-12 03:14:47