二叉树层次遍历
可以用队列实现二叉树的层次遍历
1 #include<cstdio>
2 #include<cstring>
3 #include<queue>
4 using namespace std;
5 char s[300];
6
7 struct note
8 {
9 int value;
10 note *left, *right;
11 note()
12 {
13 left=NULL;
14 right=NULL;
15 }
16 };
17 note *root=new note();
18 void addnote(int val, char *p)
19 {
20 int len=strlen(p);
21 note *u=root;
22 for(int i=0; i<len; i++)
23 {
24 if(p[i]=='L')
25 {
26 if(u->left==NULL)
27 u->left=new note();
28 u=u->left;
29 }
30 if(p[i]=='R')
31 {
32 if(u->right==NULL)
33 u->right=new note();
34 u=u->right;
35 }
36 }
37 u->value=val;
38 }
39 void inputall()
40 {
41 queue<note *> q;
42 q.push(root);
43 while(!q.empty())
44 {
45 note *u=q.front();
46 q.pop();
47 printf("%d ", u->value);
48 if(u->left!=NULL)
49 q.push(u->left);
50 if(u->right!=NULL)
51 q.push(u->right);
52 }
53 }
54 int main()
55 {
56 while(scanf("%s", s))
57 {
58 if(strcmp("()", s)==0)
59 break;
60 else
61 {
62 int val;
63 sscanf(&s[1], "%d", &val);
64 char *p;
65 p=strchr(s, ',');
66 addnote(val, p+1);
67 }
68 }
69 inputall();
70 }