要求输出 8,10,6,9,11,5,7
方法一:定义一个队列,把出队的节点的左右子树节点近队,如果左右节点为null则不用进队
1 void PrintTree( BinaryTreeNode phead ){ 2 if(phead==nuull) return ; 3 Queue<BinaryTreeNode> queue=new Queue(); 4 queue.add(phead); 5 while( queue.peek()!=null ){ 6 BinaryTreeNode pNode=queue.poll(); //出队 7 System.out.print( pNode.value); 8 9 //子节点进队 10 if(pNode.Left!=null) queue.add(pNode.Left); 11 if(pNode.Right!=null) queue.add(pNode.Right); 12 } 13 14 }
Layered print binary increased two variables used to represent a number in the current layer are not printed, a number of the lower layer represents
Void PrintTree (BinaryTreeNode Pet) { IF (Pet == nuull) return ; Queue<BinaryTreeNode> queue=new Queue(); queue.add (Pet); int nextPrint = 0; // the number of nodes in a layer of non-printed int printNum =. 1; // current number of nodes unprinted layer of the while (! queue.peek () = null ) { BinaryTreeNode pNode=queue.poll(); //出队 PrintNum--; System.out.print( pNode.value); // child node into the team IF (pNode.Left! = Null ) { queue.add(pNode.Left); ++nextPrint; } if(pNode.Right!=null) { queue.add(pNode.Right); ++nextPrint; } if(PrintNum==0){ System.out.println( ); PrintNum=nextPrint;; nextPrint;=0; } } }
Zigzag binary print l example: 8,6,10,9,11,5,7
analysis summary: the print order of the zigzag binary requires two stacks .
If the print odd-numbered layers, the first saved and then save the left node to the right node of another stack;
if the print even-numbered layers, save the first left and right node and then save the stack node to another;
1 void PrintTree( BinaryTreeNode phead ){ 2 if(phead==nuull) return ; 3 4 Stack<Integer> s0=new Stack(); //奇数 5 Stack<Integer> s1=new Stack(); //偶数 6 7 s0.push(phead); 8 9 while( !s1.empty() || !s0.empty() ){ 10 11 while(!s0.empty() ){ 12 BinaryTreeNode pNode=s0.pop(); 13 System.out.print( pNode.value ); 14 //先左后右 15 if(pNode.Letf)!=null) s1.push(pNode.Letf) ; 16 iff(pNode.Right)!=null) s1.push(pNode.Right ); 17 } 18 System.out.println(); 19 while(!s1.empty() ){ 20 BinaryTreeNode pNode=s1.pop(); 21 System.out.print( pNode.value ); 22 //先右后左 23 if(pNode.Right!=null) s0.push(pNode.Right ); 24 if(pNode.Letf)!=null) s0.push(pNode.Letf) ; 25 } 26 System.out.println(); 27 28 } 29 }