内容简介
本次作业在二叉树的建立方面,我使用了先序输入的方法来建立,即使用递归来实现。在遍历输出方面,有先序、中序、和后序三种。
其中,本次建立二叉树时,输入结束的条件为输入数据为0。
本程序创建的二叉树如下:
节点结构的创建
1 typedef struct node//创建节点结构 2 { 3 char data; 4 struct node *lchild; 5 struct node *rchild; 6 }Tree,*tree;
二叉树的建立
1 void CreateTree(tree &t)//创建二叉树 2 { 3 char ch; 4 cin>>ch; 5 if(ch == '0') t = NULL;//输入值为0是递归结束条件 6 else 7 { 8 t = (tree) new Tree; 9 if(!t) exit(0);//如果没有成功申请空间,则退出 10 t -> data = ch; 11 CreateTree(t -> lchild);//先建左子树 12 CreateTree(t -> rchild);//再建右子树 13 } 14 }
二叉树的遍历
1.先序遍历
1 void PreOrder(tree &t)//先序遍历:根结点->左子树->右子树 2 { 3 if(t) 4 { 5 cout<<t -> data;//输出节点 6 PreOrder(t -> lchild); 7 PreOrder(t -> rchild); 8 } 9 }
2.中序遍历
1 void InOrder(tree &t)//中序遍历:左子树->根结点->右子树 2 { 3 if(t) 4 { 5 InOrder(t -> lchild); 6 cout<<t -> data;//输出节点 7 InOrder(t -> rchild); 8 } 9 }
3.后序遍历
1 void PostOrder(tree &t)//后序遍历:左子树->右子树->根结点 2 { 3 if(t) 4 { 5 PostOrder(t -> lchild); 6 PostOrder(t -> rchild); 7 cout<<t -> data;//输出节点 8 } 9 }
主函数
1 int main() 2 { 3 tree t; 4 cout<<"请输入二叉树节点:(例如输入:AB00C00)"; 5 CreateTree(t); 6 cout<<"先序遍历:"; 7 PreOrder(t); 8 cout<<endl; 9 cout<<"中序遍历:"; 10 InOrder(t); 11 cout<<endl; 12 cout<<"后序遍历:"; 13 PostOrder(t); 14 cout<<endl; 15 system("pause"); 16 return 0; 17 }
运行结果
输入的值为0时代表这个是空节点
生成的是一个这样的二叉树