[Binary tree 2] print a binary tree layer by layer

Source: Internet
Author: User

[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.

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.