把二叉树打印成多行
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
一. 思路
采用层次遍历二叉树,用队列存储每一层的节点。要注意加入根节点时要判空,空则直接返回空数组出去。
二. 代码
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) { Queue<TreeNode> queue = new LinkedList<>(); ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if (pRoot == null) { return result; } queue.offer(pRoot); while (!queue.isEmpty()) { int size = queue.size(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); list.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } result.add(list); } return result; } }