题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
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<ArrayList<Integer> > ans = new ArrayList< >(); if (pRoot == null) { return ans; } Queue<TreeNode> q1 = new LinkedList<>(); q1.add(pRoot); //和普通的层序遍历区别就在于多了个flag boolean left_flag = true; while (!q1.isEmpty()) { int size = q1.size(); ArrayList<Integer> curL = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode tmp = q1.poll(); if (left_flag) { curL.add(tmp.val); } else { curL.add(0, tmp.val); } if (tmp.left != null) { q1.add(tmp.left); } if (tmp.right != null) { q1.add(tmp.right); } } ans.add(curL); left_flag = !left_flag; } return ans; } }