数据结构与算法学习记录--按层次打印二叉树结点的值
2018-03-01 19:24
344 查看
(from 牛客)
解题关键:找到当前结点所在行的最后一个结点last,找到下一行的最后一个结点nlast。层次遍历要使用队列。
初始状态:将last和nlast都指向第一个结点,将第一个结点放入队列。
以下操作在队列不为空的情况下进行:
获取队列中第一个元素,判断是否有左子树,有的话将其入队列,令nlast为左子树;判断是否有右子树,有的话将其入队列,令nlast为右子树;
判断当前结点是否为当前行的最后一个结点,即是否为last。是的话就打印标记(如打印空格)表示当前行结束,同时last指向nlast(能确定nlast一定是下一行的最后一个结点的原因是last的左右子树此时已经遍历完毕,即下一行全部结点均遍历完毕);不是则执行队列不为空时的第一步。
以下代码实现以上功能并把树中结点的值存入二维数组中,需要创建ArrayList动态二维数组临时存放树的遍历结果,然后再存入二维数组中。
解题关键:找到当前结点所在行的最后一个结点last,找到下一行的最后一个结点nlast。层次遍历要使用队列。
初始状态:将last和nlast都指向第一个结点,将第一个结点放入队列。
以下操作在队列不为空的情况下进行:
获取队列中第一个元素,判断是否有左子树,有的话将其入队列,令nlast为左子树;判断是否有右子树,有的话将其入队列,令nlast为右子树;
判断当前结点是否为当前行的最后一个结点,即是否为last。是的话就打印标记(如打印空格)表示当前行结束,同时last指向nlast(能确定nlast一定是下一行的最后一个结点的原因是last的左右子树此时已经遍历完毕,即下一行全部结点均遍历完毕);不是则执行队列不为空时的第一步。
以下代码实现以上功能并把树中结点的值存入二维数组中,需要创建ArrayList动态二维数组临时存放树的遍历结果,然后再存入二维数组中。
/* 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 Queue<TreeNode> queue = new LinkedList<>(); TreeNode last = root; TreeNode nlast = root; queue.offer(root); ArrayList<ArrayList<Integer>> raws= new ArrayList<>(); ArrayList<Integer> count = new ArrayList<>(); while(!queue.isEmpty()){ TreeNode node = queue.poll(); count.add(node.val); if(node.left!=null){ nlast = node.left; queue.offer(node.left); } if(node.right!=null){ nlast = node.right; queue.offer(node.right); } if(node == last){ last = nlast; raws.add(count); count = new ArrayList<>(); } } int[][] list = new int[raws.size()][]; for(int i = 0;i<raws.size();i++){ count = raws.get(i); int j = 0; list[i] = new int[count.size()]; for(int number : count){ list[i][j++] = number; } } return list; } }
相关文章推荐
- 数据结构与算法学习记录--二叉树的创建,递归遍历,非递归遍历的实现
- 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。 给定二叉树的根结点root,请返回打印结果,
- 《剑指Offer》学习笔记--面试题23:从上往下打印二叉树
- 按照层次遍历并打印二叉树
- 剑指offer 打印出二叉树中结点值的和为输入整数的所有路径。
- 层次打印二叉树
- 【剑指Offer学习】【面试题60:把二叉树打印出多行】
- 根据前序和中序创建二叉树及二叉树的前序、中序、后序、层次打印
- 二叉树层次遍历的螺旋打印
- 《剑指Offer》学习笔记--面试题61:按之字形顺序打印二叉树
- 题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径。
- 从上往下打印出二叉树的每个结点
- 华南理工数据结构大作业第二题 二叉树各种操作深度结点个数后序前序中序层次求祖先
- 给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
- 给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
- 从顶部开始逐层打印二叉树结点数据
- Java数据结构与算法学习记录(1)
- 数据结构与算法系列-树-二叉树的遍历(按层次遍历)
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- 写一个函数,打印二叉树中某层的所有结点