算法实现-二叉树的按层打印

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

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

解析:
这里的关键数据结构是使用队列来存储节点,因为队列是先进先出顺序,可以保证节点按照顺序弹出,问题的难点是如何换行打印,可以使用两个变量 last和nlast,一个指向当前打印的最后一个节点,一个指向下一行的最后一个节点,这样难点转换成了last和nlast的更新。nlast设置为进入队列的最新一个节点,因为最新一个节点就能保证是下一行的最后节点,last更新是当换行时,last=nlast。换行的标志是打印的当前节点是最后一个节点,假设从队列中弹出的节点为temp,即temp==last时换行。

java代码实现(该实现已经在牛客网通过):

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;
            ArrayList<ArrayList<Integer>> arrys = new ArrayList<>();
            ArrayList<Integer> line = new ArrayList<>();

            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);

            TreeNode last = root;
            TreeNode nLast = root;
            TreeNode temp = null;



            while(!queue.isEmpty()){

                temp = queue.poll();

                line.add(temp.val);

                if(temp.left!=null){
                     nLast = temp.left;
                     queue.offer(temp.left);
                }

               if(temp.right!=null){
                     nLast = temp.right;
                     queue.offer(temp.right);
                }


                if(temp == last){ // 边界这里容易出错
                    last = nLast;
                    arrys.add(new ArrayList<Integer>(line));// 这里特别容易出错,直接add(line)是不行的
                    line.clear();
                }

            }

            int rows = arrys.size();
            int result[][] = new int[rows][];
            for(int i=0;i<rows;i++){
                int columns = arrys.get(i).size();
                result[i] = new int[columns];
                for(int j=0;j<columns;j++){
                    result[i][j] =  arrys.get(i).get(j);
                }
            }
            return result;

        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值