常规思维对完全二叉树的前序遍历

 1 # include<cstdio>
 2 # include<iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     int m;
 7     int tree[1111];
 8     cin>>m;
 9     for(int i = 0; i < m; i++)
10         tree[i] = i+1;
11     int flag = 0;
12     int count = 1;
13     while(!(count == 1&&flag == 2))
14     {
15         if(flag == 0)
16         {
17             printf("%d ",tree[count-1]);
18             if(count*2 > m)
19                 flag = 1;
20             else
21                 count = count*2;
22         }
23         else if(flag == 1)
24         {
25             if(count*2+1 > m)
26                 flag = 2;
27             else
28             {
29                 count = count*2+1;
30                 flag = 0;
31             }
32         }
33         else if(flag == 2)
34         {
35             if(count%2 == 0)
36                 flag = 1;
37             else
38                 flag = 2;
39             count = count/2;
40         }
41     }
42     getchar();
43     return 0;
44 }
View Code

 

posted @ 2013-12-10 17:43  天天AC  阅读(209)  评论(0编辑  收藏  举报