1 #ifndef _TOU_H_
2 #define _TOU_H_
3 #include <iostream>
4 #include <cstdlib>
5 using namespace std;
6 #define datatype char
7 void visit(datatype item)
8 {
9 cout << item <<" ";
10 }
11
12 typedef
13 struct node
14 {
15 datatype data;
16 struct node* leftchild;
17 struct node* rightchild;
18 }bitreenode;
19 void initiate(bitreenode**root)//初始化二叉樹
20 {
21 *root = (bitreenode*)malloc(sizeof(bitreenode));
22 (*root)->leftchild = NULL;
23 (*root)->rightchild = NULL;
24 }
25
26 bitreenode* insertleftnode(bitreenode*curr, datatype x)//向該節點的左子樹插入節點
27 {
28 if (curr == NULL)
29 {
30 return NULL;
31 }
32 bitreenode* t = curr->leftchild;//保存原來節點的左子樹節點
33 bitreenode* s = (bitreenode*)malloc(sizeof(bitreenode));
34 s->data = x;
35 s->leftchild = t;//新插入節點的左子樹為原節點的左子樹
36 s->rightchild = NULL;
37
38 curr->leftchild = s;// 新節點成為curr的左子樹
39 return curr->leftchild;//返回新插入節點的指針
40 }
41
42 bitreenode* insertrightnode(bitreenode* curr, datatype x)
43 {
44 if (curr == NULL)
45 {
46 return NULL;
47 }
48 bitreenode* t = curr->rightchild;
49 bitreenode* s = (bitreenode*)malloc(sizeof(bitreenode));
50 s->data = x;
51 s->rightchild = t;//新插入節點的右子樹為原節點的右子樹
52 s->leftchild = NULL;
53
54 curr->rightchild = s;// 新節點成為curr的左子樹
55 return curr->rightchild;//返回新插入節點的指針
56 }
57
58 void destroy(bitreenode **root)
59 {
60 if ((*root) != NULL && (*root)->leftchild != NULL)
61 destroy(&(*root));
62 if ((*root) != NULL && (*root)->rightchild != NULL)
63 destroy(&(*root)->rightchild);
64 free(*root);
65 }
66
67 bitreenode* deletelefttree(bitreenode* curr)
68 {
69 if (curr == NULL || curr->leftchild == NULL) {
70 return NULL;
71 }
72 destroy(&curr->leftchild);
73 curr->leftchild = NULL;
74 return curr;
75 }
76
77 bitreenode* deleterighttree(bitreenode* curr)
78 {
79 if (curr == NULL || curr->rightchild == NULL)
80 return NULL;
81 destroy(&curr->rightchild);
82 curr->rightchild = NULL;
83 return curr;
84 }
85
86 void proorder(bitreenode* t, void visit(datatype item))//前序遍歷
87 {
88 if (t != NULL) {
89 visit(t->data);
90 proorder(t->leftchild, visit);
91 proorder(t->rightchild, visit);
92 }
93 }
94
95 void inorder(bitreenode* t, void visit(datatype item))//中序遍歷
96 {
97 if (t != NULL) {
98 inorder(t->leftchild, visit);
99 visit(t->data);
100 inorder(t->rightchild, visit);
101 }
102 }
103
104 void postorder(bitreenode* t,void visit(datatype item))//后序遍歷
105 {
106 if (t != NULL) {
107 postorder(t->leftchild, visit);
108 postorder(t->rightchild, visit);
109 visit(t->data);
110 }
111 }
112
113 void printibitree(bitreenode* br, int n)
114 {
115 int i;
116 if (br == NULL)return;//遞歸出口
117 printibitree(br->rightchild, n + 1);//遍歷打印右子樹
118 for (int i = 0; i < n; i++)cout << " ";
119 if (n >= 0)
120 {
121 cout << " " << br->data << endl;
122 }
123 printibitree(br->leftchild, n + 1);
124 }
125 #endif