本文共 970 字,大约阅读时间需要 3 分钟。
题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
实现代码:
import java.util.ArrayList;import java.util.ArrayDeque;/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { //层序遍历,因为是从左到右的打印,因此是先进先出,因此使用队列来保存元素,这里使用 //ArrayDeque来实现队列,ArrayDeque是双向队列,可以在队列头部和尾部添加和删除元素 public ArrayListPrintFromTopToBottom(TreeNode root) { ArrayList aList = new ArrayList<>(); ArrayDeque aDeque = new ArrayDeque<>(); if(root == null){ return aList; } aDeque.offerLast(root); while(!aDeque.isEmpty()){ TreeNode top = aDeque.poll(); aList.add(top.val); if(top.left != null){ aDeque.offerLast(top.left); } if(top.right != null){ aDeque.offerLast(top.right); } } return aList; }}
转载地址:http://lsnqi.baihongyu.com/