Print Binary Tree by layer -- print one layer per line

Source: Internet
Author: User

Print Binary Tree by layer -- print one layer per line

I. Problem Introduction

Given a binary tree, print the binary tree in the order of sequential traversal. However, each row needs to print a layer of data.

Ii. Algorithm Analysis

It is achieved through binary tree sequence traversal. However, two additional variables are required. One variable is used to save the number of nodes that have not been printed on the current layer, and the other variable stores the number of nodes to be printed on the next layer.

Binary Tree sequence traversal references: http://www.cnblogs.com/hapjin/p/5409921.html

Sequence printing reference:

Public void printTree (BinaryNode <T> root ){
If (root = null)
Return;
Queue <BinaryNode <T> queue = new Queue list <> ();

Int current; // number of nodes that have not been printed on the current Layer
Int next; // number of nodes in the next layer

Queue. offer (root );
Current = 1;
Next = 0;
While (! Queue. isEmpty ()){
BinaryNode <T> currentNode = queue. poll ();
System. out. printf ("%-4d", currentNode. element );
Current --;

If (currentNode. left! = Null ){
Queue. offer (currentNode. left );
Next ++;
}
If (currentNode. right! = Null ){
Queue. offer (currentNode. right );
Next ++;
}
If (current = 0 ){
System. out. println ();
Current = next;
Next = 0;
}
}
}

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.