标签:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
在获取子节点之前的队列大小就是当前层的节点个数
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 { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> layers = new ArrayList<ArrayList<Integer>>(); if (pRoot == null) return layers; Deque<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(pRoot); while (!queue.isEmpty()) { ArrayList<Integer> layer = new ArrayList<Integer>(); int cur = 0, size = queue.size(); while (cur < size) { TreeNode node = queue.poll(); layer.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } cur ++; } layers.add(layer); } return layers; } }
标签:
原文地址:http://www.cnblogs.com/wxisme/p/5835649.html