剑指offer:从上往下打印二叉树

xiaoxiao2021-02-27  137

题目描述

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

【运行时间:15ms  占用内存:8400k】

import java.util.*; public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> list=new ArrayList<Integer>(); if(root==null) return list; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode tem=queue.poll(); list.add(tem.val); if(tem.left!=null) queue.offer(tem.left); if(tem.right!=null) queue.offer(tem.right); } return list; } }

转载请注明原文地址: https://www.6miu.com/read-16922.html

最新回复(0)