从上往下打印二叉树

xiaoxiao2021-02-27  348

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

这其实就是二叉树的层次遍历: (1)访问根节点 (2)在访问第i层的时候,将i+1层的节点按顺序保存在队列中; (3)进入下一层并访问该层的所有节点; (4)重复以上操作,知道遍历完所有节点。

这里要注意,Java中的队列: LinkedList实现了Queue接 口。所以用LinkedList。 主要方法:

add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 offer 添加一个元素并返回true 如果队列已满,则返回false poll 移除并返问队列头部的元素 如果队列为空,则返回null peek 返回队列头部的元素 如果队列为空,则返回null put 添加一个元素 如果队列满,则阻塞 take 移除并返回队列头部的元素 如果队列为空,则阻塞

综上分析,代码如下:

import java.util.ArrayList; import java.util.LinkedList; /** 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> resultList = new ArrayList<Integer> (); if(root == null) return resultList; LinkedList <TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ TreeNode currentNode = queue.poll(); if(currentNode.left != null){ queue.add(currentNode.left); } if(currentNode.right != null){ queue.add(currentNode.right); } resultList.add(currentNode.val); } return resultList; } }
转载请注明原文地址: https://www.6miu.com/read-2451.html

最新回复(0)