Java编程练习:广度优先遍历二叉树并以二维数组形式打印(保留行信息)

主要思想:

  1. 设定两个 flag 变量用于标识当前打印行的末尾元素 last 以及下一行的末尾元素 nlast。
  2. 定义一个队列用以暂存二叉树节点信息。
  3. 弹出队首元素,打印出来。
  4. 从左到右将每行节点值写入队列中,最右端的右孩子节点值(即队伍最末元素)赋给 nlast。
  5. 将弹出的队首元素与 last 进行比较。若相等,则表示此时到达末尾,进入下一行,将 nlast 的值赋给 last。
  6. 重复步骤 3 到步骤 5 直至队列为空,实现二叉树广度优先遍历。
  • 刚开始的时候因为忘记了数组大小是固定的,输出格式一直不对。改了好久终于AC了。不过还是很拙劣,要加油。
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class TreePrint {
    public static void main(String[] args) {
        int[][] test = new int[5][5];
        test[0][0] = 1;
        test[0][1] = 2;
        System.out.print(test[0][0]);
    }
    public int[][] printTree(TreeNode root) {
        // 判断是否为空
        if ( root == null ) {
            throw new IllegalArgumentException();
        }
        // 暂存节点值
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode tmp = new TreeNode(0);            
        // 载入根节点
        queue.add(root);
        // 本行末
        int last = queue.getFirst().val;
        // 下一行末
        int nlast = 0;
        // 打印信息
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();     
        ArrayList<Integer> res_1 = new ArrayList<Integer>();

        while ( !queue.isEmpty() ) {
            // 根节点出队
            tmp = queue.removeFirst();
            res_1.add(tmp.val);
            if (tmp.left != null) {
                queue.add(tmp.left);
                nlast = queue.getLast().val;
            }
            if (tmp.right != null) {
                queue.add(tmp.right);
                nlast = queue.getLast().val;
            }
            // 到达行末
            if (tmp.val == last) {
                res.add(res_1);
                res_1 = new ArrayList<Integer>();
                last = nlast;
            } 
        }
        int[][] printer = new int[res.size()][];
        for (int i = 0; i < res.size(); i++) {
            printer[i] = new int[res.get(i).size()];
            for ( int j = 0; j < printer[i].length; j++ ) {
                printer[i][j] = res.get(i).get(j);
            }
        }
        return printer;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值