[Sword refers to Offer learning] [interview question 60: print the binary tree out multiple rows], sword refers to offer
Question: print a binary tree from top to bottom, print the nodes on the same layer in the order from left to right, and print a row on each layer.Solutions
Use a queue to save the nodes to be printed. To print each row of a binary tree to a single row, we need two variables: one variable indicates the number of nodes that have not been printed in the current layer, another variable represents the number of nodes next time.
Node Definition
private static class BinaryTreeNode { private int val; private BinaryTreeNode left; private BinaryTreeNode right; public BinaryTreeNode() { } public BinaryTreeNode(int val) { this.val = val; } @Override public String toString() { return val + ""; }}
Code Implementation
Import java. util. using list; import java. util. list; public class Test60 {private static class BinaryTreeNode {private int val; private BinaryTreeNode left; private BinaryTreeNode right; public BinaryTreeNode () {} public BinaryTreeNode (int val) {this. val = val ;}@ Override public String toString () {return val + "" ;}}/*** question: print a binary tree from top to bottom by layer, nodes on the same layer are printed from left to right, and one row is printed on each layer. * @ Param root */public static void print (BinaryTreeNode root) {if (root = null) {return ;}list <BinaryTreeNode> List = new Response list <> (); binaryTreeNode node; // number of nodes in the current layer int current = 1; // records the number of nodes in the next layer int next = 0; list. add (root); while (list. size ()> 0) {node = list. remove (0); current --; System. out. printf ("%-3d", node. val); if (node. left! = Null) {list. add (node. left); next ++;} if (node. right! = Null) {list. add (node. right); next ++;} if (current = 0) {System. out. println (); current = next; next = 0 ;}} public static void main (String [] args) {BinaryTreeNode n1 = new BinaryTreeNode (1 ); binaryTreeNode n2 = new BinaryTreeNode (2); BinaryTreeNode n3 = new BinaryTreeNode (3); BinaryTreeNode n4 = new BinaryTreeNode (4); BinaryTreeNode n5 = new BinaryTreeNode (5 ); required n6 = new BinaryTreeNode (6); BinaryTreeNode n7 = new BinaryTreeNode (7); BinaryTreeNode n8 = new feature (8); BinaryTreeNode feature = new BinaryTreeNode (9); n1.left = n2; n1.right = n3; n2.left = n4; n2.right = n5; n3.left = n6; n3.right = n7; n4.left = n8; n4.right = bytes; print (n1 );}}
Running result
Description
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/46857911]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.