按之字形打印二叉树
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
1 import java.util.ArrayList; 2 import java.util.Stack; 3 4 /* 5 public class TreeNode { 6 int val = 0; 7 TreeNode left = null; 8 TreeNode right = null; 9 10 public TreeNode(int val) { 11 this.val = val; 12 13 } 14 15 } 16 */ 17 public class Solution { 18 public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { 19 20 Stack<TreeNode> []level = new Stack[2]; 21 level[0] = new Stack<TreeNode>(); 22 level[1] = new Stack<TreeNode>(); 23 ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); 24 if (pRoot == null) return ans; 25 level[0].push(pRoot); 26 int now = 0; 27 ArrayList<Integer> l = new ArrayList<>(); 28 int num = 0; 29 while (!level[0].empty() || !level[1].empty()) { 30 TreeNode temp = level[now].pop(); 31 l.add(temp.val); 32 int next = (now + 1) % 2; 33 if (num % 2 == 0) { 34 if (temp.left != null) { 35 level[next].push(temp.left); 36 } 37 if (temp.right != null){ 38 level[next].push(temp.right); 39 } 40 41 } else { 42 if (temp.right != null){ 43 level[next].push(temp.right); 44 } 45 if (temp.left != null) { 46 level[next].push(temp.left); 47 } 48 49 } 50 if (level[now].empty()) { 51 now = (now + 1) % 2; 52 num++; 53 ans.add(new ArrayList<Integer>(l)); 54 l = new ArrayList<>(); 55 } 56 57 58 } 59 return ans; 60 } 61 62 }