【二叉树】二叉树打印

来源:互联网 发布:微信数据如何移到sd卡 编辑:程序博客网 时间:2024/05/22 08:21

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

举个栗子:如下就是一个二叉树

这里写图片描述

详细步骤:

1.初始化时,last=1,把1放入队列;
2.将1出队,把1的子孩子2,3放入队列,更新nlast=3;
3.nlast更新完之后,打印上一次出队的1,并和last比较,如果相同就打印换行,并更新last=nlast=3;
4.将2出队,把2的子孩子4放入队列,更新nlast=4;
5,nlast更新完以后,打印上一次出队的2,并和last(3)比较,不相同,continue;
6.将3出队,将3的子孩子5,6放入队列,更新nlast=6;
7.nlast更新完以后,打印上一次出队的3,并和last(3)比较, 相同就打印换行,并更新last=nlast=6;
…………
总结就是如下循环:(初始化last=根节点)
1.将A出队,并将A的子孩子入队,更新nlast=A最后入队的子孩子;
2.打印上次出队的家伙A,并和last比较, 如果相同就打印换行,并更新last=nlast,如果 不相同,则continue

代码如下:

import java.util.*;/*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        if(root == null){            return null;        }        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();    //提前准备一个队列queue        ArrayList<Integer> arr = new ArrayList<Integer>();        ArrayList<ArrayList<Integer>> layer = new ArrayList<ArrayList<Integer>>();        TreeNode last = root;       //正在打印的当前行的最右节点        TreeNode nlast = null;      //下一行的最右节点        queue.add(root);        while(!queue.isEmpty()){            TreeNode tem = queue.poll();//出队,将孩子添加进去            arr.add(tem.val);            if(tem.left!=null){                queue.add(tem.left);//每入队一个节点,就更新nlast                nlast = tem.left;            }            if(tem.right!=null){                queue.add(tem.right);                nlast = tem.right;            }            if(tem == last){//last出队时,更新last为last的右节点,也就是最新的nlast                layer.add(arr);                arr = new ArrayList<Integer>();                last = nlast;            }        }        //转换成二维数组        int[][] num = new int[layer.size()][];        for(int i=0;i<layer.size();i++){            num[i] = new int[layer.get(i).size()];//数组赋值前要确定长度            for(int j=0;j<layer.get(i).size();j++){                num[i][j] = layer.get(i).get(j);            }        }        return num;    }}

本题目的代码地址: 二叉树打印

我所有刷题的代码和题目的地址都在: https://github.com/zhisheng17/AlgorithmCode/

1 3