File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ // 用数组实现二叉树
2+ #include < iostream>
3+ #include < vector>
4+ #define type int
5+ using namespace std ;
6+
7+ vector<type> list;
8+ vector<type> node;
9+ vector<int > lch;
10+ vector<int > rch;
11+ int current = -1 ;
12+
13+ void create (type root)
14+ {
15+ if (node.size () == 0 )
16+ {
17+ node.push_back (root);
18+ lch.push_back (-1 );
19+ rch.push_back (-1 );
20+ current = 0 ;
21+ }
22+ }
23+
24+ void add (type e)
25+ {
26+ if (lch[current] == -1 && rch[current] == -1 )
27+ {
28+ node.push_back (e);
29+ lch.push_back (-1 );
30+ rch.push_back (-1 );
31+ lch[current] = node.size () - 1 ;
32+ }
33+ else if (rch[current] == -1 && lch[current] != -1 )
34+ {
35+ node.push_back (e);
36+ lch.push_back (-1 );
37+ rch.push_back (-1 );
38+ rch[current] = node.size () - 1 ;
39+ }
40+ if (lch[current] != -1 && rch[current] != -1 )
41+ current++;
42+ }
43+
44+ void postOrder (int index)
45+ {
46+ if (index == -1 )
47+ {
48+ return ;
49+ }
50+ postOrder (lch[index]);
51+ postOrder (rch[index]);
52+ cout << node[index] << " " ;
53+ }
54+
55+ int main ()
56+ {
57+ int n;
58+ cin >> n;
59+ for (int i = 0 ; i < n; i++)
60+ {
61+ int t;
62+ cin >> t;
63+ list.push_back (t);
64+ }
65+ create (list[0 ]);
66+ for (int i = 1 ; i < n; i++)
67+ {
68+ add (list[i]);
69+ }
70+ postOrder (0 );
71+ system (" pause" );
72+ return 0 ;
73+ }
You can’t perform that action at this time.
0 commit comments