算法之二叉树按层打印

  1. 创建一个二叉树节点实体类
/**
 1. 二叉树的 树节点 实体类
 */
public static class BinaryTreeNode {
    int value;
    BinaryTreeNode left;
    BinaryTreeNode right;
}
  1. 创建一个二叉树例子
/**

创建以下二叉树
//      1
//    /    \
//   2     3
//  / \   / \
// 4  5  6  7

 */
public static BinaryTreeNode createBinary() {
    BinaryTreeNode root = new BinaryTreeNode();
    root.value = 1;
    root.left = new BinaryTreeNode();
    root.left.value = 2;
    root.left.left = new BinaryTreeNode();
    root.left.left.value = 4;
    root.left.right = new BinaryTreeNode();
    root.left.right.value = 5;

    root.right = new BinaryTreeNode();
    root.right.value = 3;
    root.right.left = new BinaryTreeNode();
    root.right.left.value = 6;
    root.right.right = new BinaryTreeNode();
    root.right.right.value = 7;
    return root;
}
  1. 实现打印逻辑:按层级打印
/**
 * 按层级打印
 * 遍历整个二叉树,
 * 依次从当前节点打完,把该左右节点加入队列,
 * 把当前节点的右节点打完,把该右节点的子左右节点放入队列中
 * 1 2 3 4 5 6 7
 *
 * @param root 根结点
 */
public static void printFromTop2Bottom(BinaryTreeNode root) {
    if (root != null) {
        //用于存放还没遍历的元素
        Queue<BinaryTreeNode> list = new LinkedList<>();
        list.add(root);
        BinaryTreeNode currentNode;
        while (!list.isEmpty()) {
            //检索并移除队列头部数据
            currentNode = list.remove();
            System.out.print(currentNode.value + " ");
            if (currentNode.left != null) {
                list.add(currentNode.left);
            }
            if (currentNode.right != null) {
                list.add(currentNode.right);
            }
        }

    }
}

这里写图片描述

按层打印,每层换行:

 /**
 * 按层级打印,每层打印完要换行
 * 1
 * 2 3
 * 4 5 6 7
 *
 * @param root 根结点
 */
public static void printFromTop2BottomEnter(BinaryTreeNode root) {
    if (root != null) {
        Queue<BinaryTreeNode> list = new LinkedList<>();
        list.add(root);
        //当前节点
        BinaryTreeNode currentNode;
        BinaryTreeNode last = root;

        //下一行最后的节点
        BinaryTreeNode mlast = new BinaryTreeNode();
        while (!list.isEmpty()) {
            currentNode = list.remove();
            System.out.print(currentNode.value + " ");
            if (currentNode.left != null) {
                list.add(currentNode.left);
                mlast = currentNode.left;
            }
            if (currentNode.right != null) {
                list.add(currentNode.right);
                mlast = currentNode.right;
            }

            if (currentNode == last) {
                System.out.print("\n");
                last = mlast;
            }

        }
    }
}

这里写图片描述

参考
http://wiki.jikexueyuan.com/project/for-offer/question-twenty-three.html

猜你喜欢

转载自blog.csdn.net/azhansy/article/details/80207866