I. Question: enter a binary tree, print each node of the tree from top to bottom, and print it from left to right on the same layer.
For example, enter
8
/\
6 10
/\/\
5 7 9 11
Output: 8 6 10 5 7 9 11.
Ii. Analysis:
This topic mainly examines the sequence traversal of trees. The most common method is to adopt the queue form.
The elements are in the queue in the order of the left and right of the root. Then, the queue header is taken out, and the left and right subtree of the header is popped into the queue. In this way, we can traverse the entire binary tree. Some tree-like features give priority to breadth search.
3. Source Code:
# Include "stdio. H "<br/> # include" malloc. H "<br/> # include" stack. H "<br/> struct node <br/> {<br/> int data; <br/> node * right; <br/> node * left; <br/>}; <br/> node * root; <br/> void insert (node * & root, int data) <br/>{< br/> If (root = NULL) <br/>{< br/> printf ("% d \ n", data ); <br/> root = (node *) malloc (sizeof (node); <br/> root-> DATA = data; <br/> root-> right = NULL; <br/> root-> left = NULL; <br/>}< br/> else <br/> {<Br/> If (root-> data <data) // if the data to be inserted is greater than that of the node, insert the data to the right <br/> insert (root-> right, data ); <br/> else <br/> insert (root-> left, data ); <br/>}< br/> node * creattree (int A [], int N) <br/>{< br/> int I; <br/> for (I = 0; I <n; I ++) <br/> insert (root, a [I]); <br/> return root; <br/>}</P> <p> void leveltree (node * root) // sequence traversal <br/>{< br/> If (! Root) <br/> return; <br/> deque <node *> dequelist; // queue that can be inserted at both ends <br/> dequelist. push_back (Root); // insert an element to the end of the queue </P> <p> while (dequelist. size () <br/>{< br/> node * pnode = dequelist. front (); // get the queue header <br/> dequelist. pop_front (); // The queue header is displayed <br/> printf ("Data = % d \ n", pnode-> data ); <br/> If (pnode-> left) <br/> dequelist. push_back (pnode-> left); // if there is a left subtree, press its left subtree into the queue <br/> If (pnode-> right) <br/> dequelist. push_back (pnode-> right); // if the right subtree exists, press its right subtree into the queue <br/>}< br/> int main () <br/> {<br/> int A [] = {8, 6, 5, 7, 10, 9, 11}; <br/> root = creattree (A, 7 ); <br/> leveltree (Root); // use a loop </P> <p> return 0; <br/>}< br/>