标签:list node his pre highlight this 一个队列 deque lis
题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
给定的树节点结构:
public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }
二叉树的层次遍历,借助一个队列来实现。
代码如下:
public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList<>(); Queue<TreeNode> queue = new ArrayDeque<>(); if (root != null) queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); arrayList.add(node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } return arrayList; } }
标签:list node his pre highlight this 一个队列 deque lis
原文地址:https://www.cnblogs.com/yi-hui/p/8903865.html