Title Description
Implement a function to print a binary tree by its glyph, that is, the first line is printed from left to right, the second layer is printed from right to left, the third line is printed from left to right, and so on in the other rows.
Code:
<span style= "color: #000099;" >import Java.util.arraylist;import Java.util.*;/*public class TreeNode {int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) {this.val = val; }}*/public class Solution {public arraylist<arraylist<integer> > Print (TreeNode proot) {arraylist& Lt arraylist<integer>> result = new arraylist<arraylist<integer>> (); if (Proot = = null) {return result; } Boolean lefttoright = true; queue<treenode> layer = new linkedlist<treenode> (); arraylist<integer> layerlist = new arraylist<integer> (); Layer.add (Proot); int start = 0, end = 1; while (!layer.isempty ()) {TreeNode cur = layer.remove (); Layerlist.add (Cur.val); start++; if (cur.left!=null) {layer.add (cur.left); } if (Cur.right!=null) { Layer.add (Cur.right); } if (start = = end) {end = Layer.size (); start = 0; if (!lefttoright) {result.add (reverse (layerlist)); }else{Result.add (layerlist); } lefttoright =!lefttoright; Layerlist = new arraylist<integer> (); }} return result; } Private ArrayList reverse (arraylist<integer> layerlist) {int length = layerlist.size (); arraylist<integer> reverselist = new arraylist<integer> (); for (int i = length-1; I >= 0;i--) {Reverselist.add (Layerlist.get (i)); } return reverselist; }}</span>
The sword refers to the offer (53) to print the binary tree in the zigzag order