首页 > 代码库 > 二叉树

二叉树

 1 #include <iostream>
 2 using namespace std;
 3 #define SIZE 9
 4 
 5 char data[SIZE+1]={0};
 6 char pre[SIZE]={A,B,D,H,I,E,C,F,G};
 7 char mid[SIZE]={H,D,I,B,E,A,F,C,G};
 8 void preOrder(int N);
 9 void midOrder(int N);
10 void backOrder(int N);
11 void seek(int l,int r,int n,int R);
12 int main()
13 {
14     
15     seek(0,0,SIZE,1);
16     for(int i=1;i<=SIZE;i++)
17     {
18         cout <<data[i];
19     }
20     cout <<endl;
21     backOrder(1);
22     return 0;
23 }
24 
25 void seek(int l,int r,int n,int R)
26 {
27     int i;
28     int root=0;
29     i=r;
30     
31     if(n<=0)
32         return;
33     data[R]=pre[l];
34     while(mid[i]!=pre[l])
35     {
36         i++;
37         root++;
38     }
39     
40     seek(l+1,r,root,2*R);
41     seek(l+root+1,r+root+1,n-root-1,2*R+1);
42 }
43     
44 
45 
46 
47 
48 void preOrder(int N)
49 {
50     if(2*N>=SIZE+1)
51     {
52         cout << data[N];
53         return;
54     }
55     cout <<data[N];
56     preOrder(N*2);
57     if(2*N+1>=SIZE+1)
58     {
59         return;
60     }
61     preOrder(N*2+1);
62 }
63 void midOrder(int N)
64 {
65     if(2*N>=SIZE+1)
66     {
67         cout << data[N];
68         return;
69     }
70     midOrder(N*2);
71     cout << data[N];
72     if(2*N+1>=SIZE+1)
73     {
74         return;
75     }
76     midOrder(N*2+1);
77 }
78 void backOrder(int N)
79 {
80     if(2*N>=SIZE+1)
81     {
82         cout << data[N];
83         return;
84     }
85     backOrder(N*2);
86     if(2*N+1>=SIZE+1)
87     {
88         cout << data[N];
89         return;
90     }
91     backOrder(N*2+1);
92     cout << data[N];
93 }

 

二叉树