[Problem description]
Print the binary tree created in [binary tree 1] layer by layer, that is, the first line prints the 0th layer root node, and the second line prints the first layer ...... And so on.
[Example]
A binary tree is as follows:
The output is as follows:
[Code]
The beauty of programming introduces two implementations, one is recursion, and the other is the following method, each layer of the two cursor record trees. The code is only for the implementation of the function and the required header file. Does not include the definition of a binary tree node and the call of the main function.
# Include <iostream> # include <vector> using namespace std; void PrintBTreeByLevel (BTreeNode * root) {if (root = NULL) return; vector <BTreeNode *> vec; vec. push_back (root); int current = 0, last = 1; while (current <vec. size () {while (current <last) {cout <vec [current]-> value <""; if (vec [current]-> leftchild) // Avec. push_back (vec [current]-> leftchild); if (vec [current]-> rightchild) // Bvec. push_back (vec [current]-> rightchild); ++ current;} last = vec. size (); cout <endl ;}}
[Expansion 1] printing an image of a binary tree
You only need to switch the two if segments A and B in the above Code, that is, let the right child of A node into the stack and then let the left child into the stack. The result is as follows:
[Expansion 2] print a binary tree layer by layer from bottom to top
The Button to Up method is complicated. When traversing the first time, you need to apply for extra space to record the number of elements in each layer, and then reverse traversal. So recursion is used to solve the problem.