算法实现-二叉树的按层打印

xiaoxiao2021-02-28  52

题目: 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

解析: 这里的关键数据结构是使用队列来存储节点,因为队列是先进先出顺序,可以保证节点按照顺序弹出,问题的难点是如何换行打印,可以使用两个变量 last和nlast,一个指向当前打印的最后一个节点,一个指向下一行的最后一个节点,这样难点转换成了last和nlast的更新。nlast设置为进入队列的最新一个节点,因为最新一个节点就能保证是下一行的最后节点,last更新是当换行时,last=nlast。换行的标志是打印的当前节点是最后一个节点,假设从队列中弹出的节点为temp,即temp==last时换行。

java代码实现(该实现已经在牛客网通过):

import java.util.*; public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class TreePrinter { public int[][] printTree(TreeNode root) { // write code here if(root == null) return null; ArrayList<ArrayList<Integer>> arrys = new ArrayList<>(); ArrayList<Integer> line = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); TreeNode last = root; TreeNode nLast = root; TreeNode temp = null; while(!queue.isEmpty()){ temp = queue.poll(); line.add(temp.val); if(temp.left!=null){ nLast = temp.left; queue.offer(temp.left); } if(temp.right!=null){ nLast = temp.right; queue.offer(temp.right); } if(temp == last){ // 边界这里容易出错 last = nLast; arrys.add(new ArrayList<Integer>(line));// 这里特别容易出错,直接add(line)是不行的 line.clear(); } } int rows = arrys.size(); int result[][] = new int[rows][]; for(int i=0;i<rows;i++){ int columns = arrys.get(i).size(); result[i] = new int[columns]; for(int j=0;j<columns;j++){ result[i][j] = arrys.get(i).get(j); } } return result; } }
转载请注明原文地址: https://www.6miu.com/read-56250.html

最新回复(0)