DSA——二叉树习题笔记

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

public class Main {
    public int[][] printTree(TreeNode root) {
        // write code here
    	 if(root==null) return null;
    	 //竟然忘记做检查!!
    	Queue<TreeNode> queue=new LinkedList<>();
    	//能够不断添加元素的 可变的数组,不能再想办法用new int普通数组了,大家都是用的这个
    	ArrayList<Integer> array=new ArrayList<>();
    	ArrayList<ArrayList<Integer>> layer=new ArrayList<ArrayList<Integer>>();
    	queue.add(root);
    	TreeNode temp,last,nlast = null;
    	last=root;
    	while(!queue.isEmpty())
    	{
    		temp=queue.poll();
    		//temp.visit();
    		array.add(temp.val);
    		//还忘记了要检查是否为空!!!
    		if(temp.left!=null)
    		{
    			queue.add(temp.left);
        		nlast=temp.left;
    		}
    		if(temp.right!=null)
    		{
    			queue.add(temp.right);
        		nlast=temp.right;
        		
    		}
    		
    		
    		
    		//此时需要检查last是不是等于temp
    		if(last==temp)
    		{
    			last=nlast;
    			//把刚刚已经加好的array加入空的layer中
    			layer.add(array);
               //别忘了新创建一个list!!! array=new ArrayList<>(); } } //把arrayList转化为数组 int[][] result=new int[layer.size()][]; for(int i=0;i<layer.size();i++) { //因为是相当于二维的,所以用arraylist。get()获取的元素就是原来的那个 result[i]=new int[layer.get(i).size()]; for(int j=0;j<layer.get(i).size();j++) result[i][j]=layer.get(i).get(j); } return result; } }

  

原文地址:https://www.cnblogs.com/Cherrylalala/p/6621888.html