一、题目
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
二、思路
队列LinkedList完成层序遍历,用end记录每层结点数目
三、代码
import java.util.ArrayList; import java.util.LinkedList; /* * 队列LinkedList完成层序遍历,用end记录每层结点数目 */ public class Solution { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { //保存结果 ArrayList<ArrayList<Integer>> result = new ArrayList<>(); //预检验 if (pRoot == null) { return result; } LinkedList<TreeNode> layer = new LinkedList<>(); ArrayList<Integer> layerList = new ArrayList<>(); layer.add(pRoot); int start = 0, end = 1; while (!layer.isEmpty()) { TreeNode cur = layer.remove(); layerList.add(cur.val); start++; if (cur.left != null) { layer.add(cur.left); } if (cur.right != null) { layer.add(cur.right); } if (start == end) { end = layer.size(); start = 0; result.add(layerList); layerList = new ArrayList<>(); } } return result; } }
View Code
———————————————
参考链接:
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking