按之字形遍历二叉树-Java
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
一. 思路
核心思想是采用广度优先遍历算法,遍历二叉树的每一层,用LinkedList存储每一层的节点。遍历LinkedList就是遍历二叉树的每一层。
二. 代码
import java.util.ArrayList; import java.util.List; import java.util.LinkedList; /* 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) { LinkedList<TreeNode> q = new LinkedList<>(); ArrayList<ArrayList<Integer>> res = new ArrayList<>(); boolean flag = true; q.add(pRoot); while (!q.isEmpty()) { int size = q.size(); ArrayList<Integer> list = new ArrayList<Integer> (); for (int i = 0; i < size; i++) { TreeNode node = q.poll(); if(node == null) continue; if(flag){ list.add(node.val); } else { list.add(0, node.val); } q.add(node.left); q.add(node.right); } if (list.size() != 0) res.add(list); flag = !flag; } return res; } }