• 二叉树的层次遍历(按层换行打印)


    概述

    二叉树的层次遍历只需使用一个队列即可,但若需要按层来换行打印则稍麻烦一些。

    思路

    增加两个TreeNode:last和nlast
    last:表示当前遍历层最右结点
    nlast:表示下一层最右结点
    遍历时,每次将nlast指向插入队列元素,最后一个插入结点时即最右结点。插入左右孩子之后,检测last是否为当前输出结点,若是,则表示需要进行换行,并将last指向下一层的nlast。

    代码

    /*
    public class TreeNode {
        int data;
        TreeNode left;
        TreeNode right;
    
        public TreeNode(int data) {
            this.data = data;
        }
    }
    */
    public class Tree {
        TreeNode last;
        TreeNode nlast;
        public void printTree(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            last = root;
            nlast = root;
            while (!queue.isEmpty()) {
                TreeNode t = queue.peek();
                System.out.print(queue.poll().data + " ");
                if (t.left != null) {
                    queue.add(t.left);
                    nlast = t.left;
                }
                if (t.right != null) {
                    queue.add(t.right);
                    nlast = t.right;
                }
                // 如果当前输出结点是最右结点,那么换行
                if (last == t) {
                    System.out.println();
                    last = nlast;
                }
            }
        }
    
        public static void main(String[] args) {
            // 构建二叉树
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(3);
            root.left.left = new TreeNode(4);
            root.right.left = new TreeNode(5);
            root.right.right = new TreeNode(6);
            root.right.left.left = new TreeNode(7);
            root.right.left.right = new TreeNode(8);
            Tree test = new Tree();
            test.printTree(root);
        }
    }
    
  • 相关阅读:
    S5PV210开发板刷机(SD卡uboot、串口+USB-OTG刷机方法)
    S5PV210启动过程分析
    总结:ARM逻辑和高级C(朱老师物联网学习)
    C语言笔记(数组地址一些细节)
    shell脚本和常用命令
    ansible
    firewalld
    LAMP架构上线动态网站WordPress
    LNMP架构上线动态网站
    Tomcat集群 Nginx负载均衡 shell脚本实时监控Nginx
  • 原文地址:https://www.cnblogs.com/zyoung/p/7455916.html
Copyright © 2020-2023  润新知