![](https://img2018.cnblogs.com/blog/1239274/201812/1239274-20181210201453584-1893813631.jpg)
1 #include<iostream>
2 #include<cstdio>
3 #include<malloc.h>
4 #include<cstring>
5 using namespace std;
6
7 typedef char Elemtype;
8
9 typedef struct BiTNode{
10 char data;
11 struct BiTNode *lchild,*rchild;
12 }BiTNode,*BiTree;
13
14 //创建一颗二叉树,约定遵照用户前序遍历输入数据
15 void CreateBiTree(BiTree &T){
16 char c;
17 scanf("%c",&c);
18 if(c==' ')
19 T=NULL;
20 else
21 {
22 T = (BiTNode *)malloc(sizeof(BiTNode));
23 T->data = c;
24 CreateBiTree(T->lchild);
25 CreateBiTree(T->rchild);
26 }
27 }
28
29 void visit(char c,int level){
30 printf("%c在树中第%d层\n",c,level);
31 }
32
33 //前序遍历二叉树
34 void PreOrderTraverse(BiTree &T, int level){
35 if(T){
36 visit(T->data,level);
37 PreOrderTraverse(T->lchild,level+1);
38 PreOrderTraverse(T->rchild,level+1);
39 }
40 }
41
42 int main(){
43 int level = 1;
44 BiTree T = NULL;
45 CreateBiTree(T);
46 PreOrderTraverse(T,level);
47 return 0;
48 }
![](https://img2018.cnblogs.com/blog/1239274/201812/1239274-20181210201532588-478146096.jpg)