算法题:二叉树打印

来源:互联网 发布:python 编码转换 编辑:程序博客网 时间:2024/06/05 09:44

1.题目

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

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

/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class TreePrinter {    public int[][] printTree(TreeNode root) {        //write code here    }}    

2.思路

借用一个队列,以层次遍历的思想,来解答。关键点在于,判断什么时候该换层了

  1. last指向当前正在打印的行的最右边的节点。
  2. nLast指向当前入队的节点。
  3. 从根结点开始,将其左右孩子以层次遍历的方式入队。每入队一个元素,即让nLast指向这个元素,将队首元素temp出队到一个ArrayList中,当temp==last时,代表该换行了,也就是将当前ArrayList放到一个ArrayLists中,再讲当前的ArrayList清空。然后last=nLast;

3.代码

public int[][] printTree(TreeNode root) {        if(root==null)            return null;        int[][]result=null;        TreeNode last=root;        TreeNode nLast=null;        TreeNode temp=null;        ArrayList<Integer>array=new ArrayList<>();        ArrayList<ArrayList<Integer>> arrays=new ArrayList<>();        LinkedList<TreeNode>queue=new LinkedList<>();        queue.add(last);        while(!queue.isEmpty()){            temp=queue.poll();            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;            }            if(temp==last){                arrays.add(array);                array=new ArrayList<>();                last=nLast;            }        }          result=new int[arrays.size()][];        for(int i=0;i<arrays.size();i++){            result[i]=new int[arrays.get(i).size()];            for(int j=0;j<arrays.get(i).size();j++){                result[i][j]=arrays.get(i).get(j);            }        }       return result;     }

需要注意ArrayList<ArrayList<Integer>>转换成int[][]的方法

0 0
原创粉丝点击