博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer——从上到下打印二叉树
阅读量:4227 次
发布时间:2019-05-26

本文共 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 ArrayList
PrintFromTopToBottom(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/

你可能感兴趣的文章
Pro .NET 2.0 Windows Forms and Custom Controls in VB 2005
查看>>
RSA Security's Official Guide to Cryptography
查看>>
Artificial Intelligence for Games
查看>>
SQL Server 2005 Bible
查看>>
Distributed Systems Architecture: A Middleware Approach
查看>>
Beginning XML, 4th Edition
查看>>
Beginning JavaScript, 3rd Edition
查看>>
The TCP/IP Guide: A Comprehensive, Illustrated Internet Protocols Reference [ILLUSTRATED]
查看>>
Fault-Tolerant Systems
查看>>
C Programming for Scientists and Engineers
查看>>
Pragmatic Software Testing: Becoming an Effective and Efficient Test Professional
查看>>
Struts: The Complete Reference, 2nd Edition
查看>>
MCITP Developer: Microsoft SQL Server 2005 Database Solutions Design
查看>>
Text Entry Systems: Mobility, Accessibility, Universality
查看>>
CliffsTestPrep Cisco CCNA
查看>>
Pro PayPal E-Commerce
查看>>
A Guide to MATLAB Object-Oriented Programming
查看>>
Outlook 2007: Beyond the Manual
查看>>
SharePoint 2007 User's Guide: Learning Microsoft's Collaboration and Productivity Platform
查看>>
Word 2007: Beyond the Manual
查看>>