Topic:
There is a binary tree, please design an algorithm, according to the level print this binary tree. Root node of a given binary tree,
Please return the printed result, and the results are stored in an array of each layer, and the order of all the arrays follows the number of layers from top to bottom, and the elements in each layer array are arranged from left to Right. Guaranteed node count is less than or equal to 500.
Problem solving Ideas:
Similar to the ideas in the previous article
Source:
packagess.entity; public classTreeNode {intval; TreeNode left; TreeNode right; public intgetval () {returnval; } public voidSetval (intVal) { this. val =val; } publicTreeNode getLeft () {returnleft ; } public voidsetleft (TreeNode Left) { this. left =left ; } publicTreeNode getRight () {returnright ; } public voidsetright (TreeNode Right) { this. right =right ; } publicTreeNode (intX) {val =x;} public Booleanequals (Object obj) {return Super. Equals (obj); }}
packagess.tree;Importjava.util.ArrayList;Importjava.util.LinkedList;Importjava.util.List;Importjava.util.Queue;Importss.entity.TreeNode;/*** There is a binary tree, please design an algorithm, according to the level print this binary tree. * Root of the given binary tree, * Please return the printout, * The results are stored in an array of each layer, * The order of all arrays follows the number of layers from top to bottom, and the elements in each layer are arranged from left to Right. Guaranteed node count is less than or equal to 500. * */ public classTreeDemo03 { public Static voidmain (string[] Args) {TreeNode tree=NewTreeNode (1); Tree.setleft (NewTreeNode (2)); Tree.setright (NewTreeNode (3)); Tree.getleft (). Setleft (NewTreeNode (4)); Tree.getright (). Setleft (NewTreeNode (5)); Tree.getright (). Setright (NewTreeNode (6)); Tree.getright (). getLeft (). setleft (NewTreeNode (7)); Tree.getright (). getLeft (). setright (NewTreeNode (8)); int[] A =Treedemo03.printtree (tree); for(int[] B:a) { for(intC:b) {System.out.print (c); } System.out.println (); } } public Static int[] printtree (TreeNode root) {TreeNode last=root; TreeNode Nlast=NULL; Queue Queue=NewLinkedList (); Queue.add (root); List<List> List =NewArraylist<list>(); List<Integer> temp =NewArraylist<integer>(); intMaxWidth = 0; while(!Queue.isempty ()) {TreeNode Tempnode=(TreeNode) Queue.poll (); Temp.add (tempnode.getval ()); if(NULL!=Tempnode.getleft ()) {queue.add (tempnode.getleft ()); Nlast=Tempnode.getleft (); } if(NULL!=Tempnode.getright ()) {queue.add (tempnode.getright ()); Nlast=Tempnode.getright (); } if(tempnode.equals (last)) { last=nlast; List.add (temp); if(temp.size () >MaxWidth) maxWidth=temp.size (); Temp=NewArraylist<integer>(); }Else{ Continue; } } int[[] result =New int[list.size ()][maxwidth]; for(inti = 0; I < list.size (); i++) {List<Integer> LL =List.get (i); for(intj = 0; J < list.get (i). size (); J + +) {result[i][j]=Ll.get (j); } } returnresult; }}
Java Width precedence two-fork tree array