头文件(bitree.hpp)
1 #pragma
2 #include<iostream>
3 #include<queue>
4 #include<vector>
5 #include<stack>
6 using namespace std;
7 struct TreeNode
8 {
9 int NodeData;
10 TreeNode *pLeft;
11 TreeNode *pRight;
12 TreeNode(int x) :NodeData(x), pLeft(NULL),pRight(NULL) {}
13 };
14 class Mytree
15 {
16 public:
17 void insertTree(TreeNode* proot,int n)
18 {
19
20 }
21 void PreOrderno(TreeNode *T)//前序遍历,递归
22 {
23 if (!T)
24 return;
25 if (T)
26 {
27 cout << T->NodeData << endl;
28 PreOrderno(T->pLeft);
29 PreOrderno(T->pRight);
30
31 }
32
33 }
34 void PreOrder(TreeNode *T)//非递归,前序遍历
35 {
36 if (T == NULL)
37 {
38 return;
39 }
40 stack<TreeNode*>s;
41 s.push(T);
42 TreeNode *temp;
43 while (!s.empty())
44 {
45 temp = s.top();
46 cout << temp->NodeData;
47 s.pop();
48 if (temp->pLeft)
49 {
50 s.push(temp->pLeft);
51 }
52 if (temp->pRight)
53 {
54 s.push(temp->pRight);
55 }
56 }
57 }
58
59 void InOrder(TreeNode *T)//中序遍历
60 {
61 if (!T)
62 return;
63 InOrder(T->pLeft);
64 cout << T->NodeData;
65 InOrder(T->pRight);
66 }
67
68 void PostOrder(TreeNode *T)//后序遍历
69 {
70 if (!T)
71 return;
72 PostOrder(T->pLeft);
73 PostOrder(T->pRight);
74 cout << T->NodeData;
75 }
76 void Levelorder(TreeNode *T)//层析遍历
77 {
78 if (!T)
79 return;
80 TreeNode *temp;
81 queue<TreeNode*>q;
82 q.push(T);
83 while (!q.empty())
84 {
85 temp = q.front();
86 cout << temp->NodeData;
87 if (temp->pLeft)
88 q.push(temp->pLeft);
89 if (temp->pRight)
90 q.push(temp->pRight);
91 q.pop();
92 }
93 }
94 void DeepOrder(TreeNode *T)//深度遍历
95 {
96 if (!T)
97 return;
98 TreeNode *temp;
99 stack<TreeNode*>s;
100 s.push(T);
101 while (!s.empty())
102 {
103 temp = s.top();
104 cout << temp->NodeData;
105 s.pop();
106 if (temp->pLeft)
107 s.push(temp->pLeft);
108 if (temp->pRight)
109 s.push(temp->pRight);
110 }
111 }
112 private:
113
114 };
1 #include "bitree.hpp" 2 int main() 3 { 4 Mytree mytree; 5 TreeNode *pRoot; 6 7 TreeNode node1(1); 8 TreeNode node2(2); 9 TreeNode node3(3); 10 TreeNode node4(4); 11 TreeNode node5(5); 12 TreeNode node6(6); 13 TreeNode node7(7); 14 TreeNode node8(8); 15 pRoot = &node1; 16 node1.pLeft = &node2; 17 node1.pRight = &node3; 18 node2.pLeft = &node4; 19 node2.pRight = &node5; 20 node3.pLeft = &node6; 21 node3.pRight = &node7; 22 node4.pLeft = &node8; 23 //深度遍历 24 cout << "前序遍历:" << endl; 25 mytree.PreOrderno(pRoot); 26 cout << "深度遍历:" << endl; 27 mytree.DeepOrder(pRoot); 28 cout << "中序遍历:" << endl; 29 mytree.InOrder(pRoot); 30 cout << "层析遍历:" << endl; 31 mytree.Levelorder(pRoot); 32 cout << "前序非递归遍历:" << endl; 33 34 mytree.PreOrder(pRoot); 35 cout << "后续遍历:" << endl; 36 mytree.PostOrder(pRoot); 37 38 }