22 从下往上打印二叉树

题目:从上往下打印二叉树

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

 

 1 import java.util.ArrayList;
 2 import java.util.*;
 3 /**
 4 public class TreeNode {
 5     int val = 0;
 6     TreeNode left = null;
 7     TreeNode right = null;
 8 
 9     public TreeNode(int val) {
10         this.val = val;
11     }
12 }
13 */
14 public class Solution {
15     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
16         ArrayList<Integer> array = new ArrayList<Integer>();
17         //考虑特殊情况
18         //调试代码的时候,此处若返回null,则报错java.lang.NullPointerException;若返回array,则正确
19         if(root== null) return array;
20         //声明一个队列,用队列来辅助;声明一个中间节点,作为循环中使用的遍历节点
21         //./Solution.java:21: error: Queue is abstract; cannot be instantiated
22         //Queue Q = new Queue();
23         //^
24         //1 error
25         Queue<TreeNode> Q = new LinkedList<TreeNode>();
26         TreeNode temp = null;
27         Q.add(root);
28         while(!Q.isEmpty()){
29             temp = Q.poll();
30             array.add(temp.val);
31             if(temp.left !=null) Q.add(temp.left); //用offer来入队也可以
32             if(temp.right !=null) Q.add(temp.right);
33         }
34         return array;
35     }
36 }

 

 

 

 

遇到的问题: Queue<TreeNode> Q = new Queue<TreeNode>();语句总是报错,原因是cannot instantiate the type

       更改为Queue<TreeNode> Q = new LinkedList<TreeNode>();才正确

关于Queue的初始化:http://www.cnblogs.com/yuansc/p/9087044.html

本地编译器的代码

 (TODOLIST)

 

牛客网上另外一个代码,底下的评论值得借鉴一下

利用两个ArrayList去实现,相应采取的也是ArrayList中的方法

 1 public class Solution {
 2     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
 3         ArrayList<Integer> list = new ArrayList<>();
 4         ArrayList<TreeNode> queue = new ArrayList<>();
 5         if (root == null) {
 6             return list;
 7         }
 8         queue.add(root);
 9         while (queue.size() != 0) {
10             TreeNode temp = queue.remove(0);
11             if (temp.left != null){
12                 queue.add(temp.left);
13             }
14             if (temp.right != null) {
15                 queue.add(temp.right);
16             }
17             list.add(temp.val);
18         }
19         return list;
20     }
21 }

 

remove(0)删除queue的第一个元素并将其返回,模拟了队列的弹出操作

我觉得这才是出题人的意图吧,毕竟题目只给出了 import java.util.ArrayList;,如果直接用队列,那不就失去意义了么

ArrayList的话,queue.remove(0)这个耗时会很高,应该用LinkedList

出题人不严谨,思路都是一样的,不过用ArrayList每次删除都会System.arraycopy,消耗很严重。还不如用链队列,LinkedList去实现会好得多

arrayList每次删除都要复制数组不太好啊

 

转载于:https://www.cnblogs.com/shareidea94/p/10882371.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值