Differences Between Binary Tree and non-recursive Traversal

Source: Internet
Author: User
Tags root access
1 # include & lt; iostream & gt; 23 # defineMAXN1004usingnamespacestbd; 567structBTNode8 {9 chartag; 10BTNode * left; 11BTNode * right; 12}; 1314classBTree15 {16pri...

1 # include
2
3 # define MAXN 100
4 using namespace stbd;
5
6
7 struct BTNode
8 {
9 char tag;
10 BTNode * left;
11 BTNode * right;
12 };
13
14 class BTree
15 {
16 private:
17 BTNode ** root;
18 void BuildBTree (BTNode ** root );
19
20 public:
21/* recursive version */
22 void PreVisit (BTNode * root );
23 void InVisit (BTNode * root );
24 void PostVisit (BTNode * root );
25
26/* Non-recursive version */
27 void NR_PreVisit (BTNode * root );
28 void NR_InVisit (BTNode * root );
29 void NR_PostVisit (BTNode * root );
30
31 BTree (BTNode ** r );
32 BTree ();
33 };
34
35 BTree: BTree ()
36 {
37
38}
39
40 BTree: BTree (BTNode ** r)
41 {
42 root = r;
43 /*
44 * root = new BTNode; 45 (* root)-> left = NULL;
46 (* root)-> right = NULL; 47 */
48 BuildBTree (root );
49}
50
51/* Insert nodes in the FIFO mode */
52 void BTree: BuildBTree (BTNode ** root)
53 {
54 char c;
55
56 c = getchar ();
57 if (c = '#')
58 * root = NULL;
59 else {
60 * root = new BTNode;
61 (* root)-> tag = c;
62 BuildBTree (& (* root)-> left );
63 BuildBTree (& (* root)-> right );
64}
65}
66
67 void BTree: PreVisit (BTNode * root)
68 {
69 if (root! = NULL)
70 {
71 printf ("% c", root-> tag );
72 PreVisit (root-> left );
73 PreVisit (root-> right );
74}
75}
76
77 void BTree: InVisit (BTNode * root)
78 {
79 if (root! = NULL)
80 {
81 InVisit (root-> left );
82 printf ("% c", root-> tag );
83 InVisit (root-> right );
84}
85}
86
87 void BTree: PostVisit (BTNode * root)
88 {
89 if (root! = NULL)
90 {
91 PostVisit (root-> left );
92 PostVisit (root-> right );
93 printf ("% c", root-> tag );
94}
95}
96
97 void BTree: NR_PreVisit (BTNode * root)
98 {
99 BTNode * s [MAXN];
100 int top = 0;
101
102 while (top! = 0 | root! = NULL)
103 {
104 while (root! = NULL)
105 {
106 s [top] = root;
107 printf ("% c", s [top ++]-> tag );
108 root = root-> left;
109}
110 if (top> 0)
111 {
112 root = s [-- top];
113 root = root-> right;
114}
115}
116}
117
118 void BTree: NR_InVisit (BTNode * root)
119 {
120 BTNode * s [MAXN];
121 int top = 0;
122
123 while (top! = 0 | root! = NULL)
124 {
125 while (root! = NULL)
126 {
127 s [top ++] = root;
128 root = root-> left;
129}
130 if (top> 0)
131 {
132 root = s [-- top];
133 printf ("% c", root-> tag );
134 root = root-> right;
135}
136}
137}
138
139 void BTree: NR_PostVisit (BTNode * root)
140 {
141 BTNode * s [MAXN], * tmp = NULL;
142 int top = 0;
143
144 while (top! = 0 | root! = NULL)
145 {
146 while (root! = NULL)
147 {
148 s [top ++] = root;
149 root = root-> left;
150}
151 if (top> 0)
152 {
153 root = s [-- top];
154
155/* The right child does not exist or has been accessed. the root user goes out of the stack and accesses it */
156 if (root-> right = NULL) | (root-> right = tmp ))
157 {
158 printf ("% c", root-> tag );
159 tmp = root; // Save the root pointer
160 root = NULL; // The current pointer is NULL to prevent stack re-entry
161}
162
163/* do not go out of stack, continue to access the right child */
164 else
165 {
166 top ++; // balance with root = s [-- top]
167 root = root-> right;
168}
169}
170}
171}
172
173 int main ()
174 {
175 BTNode * root = NULL;
176 BTree bt (& root); // address of the header pointer
177
178 bt. NR_PreVisit (root );
179 printf ("\ n ");
180 bt. NR_InVisit (root );
181 printf ("\ n ");
182 bt. NR_PostVisit (root );
183 printf ("\ n ");
184 return 0;
185}

First, run the code. tb with NR (Non-recursive) indicates Non-recursive traversal.

 

Test data:

124 #8 ## 5 ## 369 ### 7 ##

 

Binary Tree:

 

It is indeed rough to draw pictures that come with windows...

 

Test results:

1 2 4 8 5 3 6 9 7
4 8 2 5 1 9 6 3 7
8 4 5 2 9 6 7 3 1

 

 

I. Establishment of Binary Trees

 

First of all, pay attention to the process of creating a binary tree. Here we use the first-order method to recursively insert nodes. Therefore, when inputting data, we must first input data in order,

If the Left or Right node is empty, # is used. Otherwise, the input will not respond, because the recursion process is not over yet, and pressing CTRL + Z is useless. Of course, you can use

Insert in other ways (such as recursive insertion in the middle sequence and recursive insertion in the back sequence ).

 

Ii. Differences between the three types of non-recursive Traversal

 

Recursive traversal of the forward, middle, and backward orders is relatively simple. Instead of recursive traversal, you only need to use an array to store node pointers and simulate the operating mechanism of the system stack.

First, describe non-recursive traversal. If you access the node in the root-left-right mode, you need to press the current node to stack (print the current node information at the same time ), until the left subtree is empty (inner while); then the stack is output and accessed

Right node; the subsequent operations are the same as those above (outer while ).

For non-recursive traversal of the central order, we can see that the code structure is almost identical, but the locations of the printed node information are different. This is because the central order traversal is left-root-right, so that the forward order and the central order are not

Recursive traversal (root-left and left-root are both stack-pressed actions, and the objects of the stack-outbound actions are all parent nodes) is consistent.

 

For post-Order Non-recursive traversal, because the post-order traversal is left-right-root, and the root access is after the right child, this means two situations:

1. the right child is not blank (continue to access the right child );

2. If the right child is empty and returns from the left child, you need to access the root node.

To distinguish between the two cases (the physical form is returned from the left child, or the right child returns to access the root node ), for access to the right child, you need to determine whether the right child of the root node is empty or has

Accessed (the right subtree has been traversed ). In both cases, you should not access the root node, but continue to enter the right subtree.

  

Iii. Additional instructions

 

In the post-Order Non-recursive traversal else statements, top ++ is purely designed to balance the stack, because for 2) to continue accessing the right child, no need to go out of the stack, the preceding root [-- top] contains

To ensure the correctness of the stack (of course there can be other processing, here we also consider the uniformity of the three non-recursive traversal methods ).

The two while statements do not increase the time complexity of the program, because the number of nodes in the binary tree is fixed, and the while statements in the inner layer are used to improve the logic of the algorithm.

 

Iv. recursion-> non-recursion

 

In addition, I saw a non-recursive code written by a teacher during my internship today. It's great. I like it! It only saves the return address of the program and the form parameters and local variables of the function, and then exits

Restore the scene. It is also non-recursive, but this method is closer to the compiler's processing method, and is consistent with the Task Switching in the operating system. Therefore, this method lays the foundation for Recursive automatic conversion to non-recursive.

Set the foundation.

Share the non-recursive tower he wrote on the spot:

 


1 # include
2 # include
3
4 using namespace std;
5
6 # define MAXSIZE 1000
7
8 struct SNode
9 {
10 int n;
11 char from;
12 char;
13 char aux;
14 int label;
15 };
16
17 struct STK
18 {
19
20 SNode stack [MAXSIZE];
21 int sp;
22 STK ()
23 {
24 sp = 0;
25 };
26 void push (int n, char from, char to, char aux, int label)
27 {
28 if (sp> = MAXSIZE)
29 {
30 printf ("STK is full! \ N ");
31}
32 stack [sp]. n = n;
33 stack [sp]. from = from;
34 stack [sp]. to =;
35 stack [sp]. aux = aux;
36 stack [sp ++]. label = label;
37 };
38 SNode POP ()
39 {
40 if (sp <= 0)
41 {
42 printf ("STK is empty! \ N ");
43}
44 return stack [-- sp];
45 };
46 };
47
48 void move (int n, char from, char to, char aux)
49 {
50 if (n = 1)
51 {
52 cout <"detach #1 disk from" < 53}
54 else
55 {
56 move (n-1, from, aux, );
57 cout <"yes #" < 58 move (n-1, aux, to, from );
59}
60}
61
62
63 void move_stk (int n, char from, char to, char aux)
64 {
65 STK stk;
66 char tmp;
67 S1:
68 if (n = 1)
69 {
70 cout <"detach #1 disk from" < 71}
72 else
73 {
74 stk. push (n, from, to, aux, 2 );
75 n = n-1;
76 tmp =;
77 to = aux;
78 aux = tmp;
79 goto S1;
80 // move (n-1, from, aux, );
81 S2:
82 cout <"yes #" < 83
84 stk. push (n, from, to, aux, 3 );
85 n = n-1;
86 tmp = from;
87 from = aux;
88 aux = tmp;
89 goto S1;
90 // move (n-1, aux, to, from );
91}
92 S3:
93 if (stk. sp> 0)
94 {
95 SNode sn = stk. POP ();
96 n = sn. n;
97 from = sn. from;
98 to = sn.;
99 aux = sn. aux;
100 if (1 = sn. label)
101 goto S1;
102 else if (2 = sn. label)
103 goto S2;
104 else
105 goto S3;
106}
107}
108
109
110
111 int main (int argc, char * argv [])
112 {
113 move (3, 'A', 'B', 'C ');
114 printf ("=============================================\ n ");
115 move_stk (3, 'A', 'B', 'C ');
116
117 return 0;
118}

Author: tbwshc
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.