美文网首页
[算法] - 树的遍历以及优美打印

[算法] - 树的遍历以及优美打印

作者: 夹胡碰 | 来源:发表于2022-03-02 11:28 被阅读0次

话不多说,直接上代码

import java.util.LinkedList;
import java.util.Queue;

public class BaseTree {

    public static void main(String[] args) {
        TreeNode treeNode = buildTreeNode(2);
        TreeOperation.beautifulShow(treeNode);
        System.out.println("<==============深度优先遍历==============>");
        deepShow(treeNode);
        System.out.println("<==============广度优先便利==============>");
        spanShow(treeNode);
    }

    protected static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    protected static TreeNode buildTreeNode(int level){
        int i = 1;
        TreeNode treeNode = new TreeNode(i++);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(treeNode);
        int size = 1;
        while (level-- > 0) {
            size *= 2;
        }

        while (--size > 0) {
            TreeNode poll = queue.poll();
            poll.left = new TreeNode(i++);
            poll.right = new TreeNode(i++);
            queue.offer(poll.left);
            queue.offer(poll.right);
        }

        return treeNode;
    }

    protected static void deepShow(TreeNode treeNode) {
        StringBuffer a1 = new StringBuffer();
        StringBuffer a2 = new StringBuffer();
        StringBuffer a3 = new StringBuffer();
        show(treeNode, a1, a2, a3);
        System.out.println("前序遍历: " + a1);
        System.out.println("中序遍历: " + a2);
        System.out.println("后序遍历: " + a3);
    }

    private static void show(TreeNode treeNode, StringBuffer a1, StringBuffer a2, StringBuffer a3){
        if (treeNode == null) {
            return;
        }
        a1.append(treeNode.val).append(" ");
        show(treeNode.left, a1, a2, a3);
        a2.append(treeNode.val).append(" ");
        show(treeNode.right, a1, a2, a3);
        a3.append(treeNode.val).append(" ");
    }

    private static void spanShow(TreeNode treeNode){
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(treeNode);
        System.out.print("广度遍历: ");
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            if (poll == null) {
                continue;
            }
            System.out.print(poll.val + " ");
            queue.offer(poll.left);
            queue.offer(poll.right);
        }
    }



    public static class TreeOperation {
    /*
    树的结构示例:
              1
            /   \
          2       3
         / \     / \
        4   5   6   7
    */

        // 用于获得树的层数
        public static int getTreeDepth(TreeNode root) {
            return root == null ? 0 : (1 + Math.max(getTreeDepth(root.left), getTreeDepth(root.right)));
        }


        private static void writeArray(TreeNode currNode, int rowIndex, int columnIndex, String[][] res, int treeDepth) {
            // 保证输入的树不为空
            if (currNode == null) {return;}
            // 先将当前节点保存到二维数组中
            res[rowIndex][columnIndex] = String.valueOf(currNode.val);

            // 计算当前位于树的第几层
            int currLevel = ((rowIndex + 1) / 2);
            // 若到了最后一层,则返回
            if (currLevel == treeDepth) {return;}
            // 计算当前行到下一行,每个元素之间的间隔(下一行的列索引与当前元素的列索引之间的间隔)
            int gap = treeDepth - currLevel - 1;

            // 对左儿子进行判断,若有左儿子,则记录相应的"/"与左儿子的值
            if (currNode.left != null) {
                res[rowIndex + 1][columnIndex - gap] = "/";
                writeArray(currNode.left, rowIndex + 2, columnIndex - gap * 2, res, treeDepth);
            }

            // 对右儿子进行判断,若有右儿子,则记录相应的"\"与右儿子的值
            if (currNode.right != null) {
                res[rowIndex + 1][columnIndex + gap] = "\\";
                writeArray(currNode.right, rowIndex + 2, columnIndex + gap * 2, res, treeDepth);
            }
        }


        public static void beautifulShow(TreeNode root) {
            if (root == null) {System.out.println("EMPTY!");}
            // 得到树的深度
            int treeDepth = getTreeDepth(root);

            // 最后一行的宽度为2的(n - 1)次方乘3,再加1
            // 作为整个二维数组的宽度
            int arrayHeight = treeDepth * 2 - 1;
            int arrayWidth = (2 << (treeDepth - 2)) * 3 + 1;
            // 用一个字符串数组来存储每个位置应显示的元素
            String[][] res = new String[arrayHeight][arrayWidth];
            // 对数组进行初始化,默认为一个空格
            for (int i = 0; i < arrayHeight; i ++) {
                for (int j = 0; j < arrayWidth; j ++) {
                    res[i][j] = " ";
                }
            }

            // 从根节点开始,递归处理整个树
            // res[0][(arrayWidth + 1)/ 2] = (char)(root.val + '0');
            writeArray(root, 0, arrayWidth/ 2, res, treeDepth);

            // 此时,已经将所有需要显示的元素储存到了二维数组中,将其拼接并打印即可
            for (String[] line: res) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < line.length; i ++) {
                    sb.append(line[i]);
                    if (line[i].length() > 1 && i <= line.length - 1) {
                        i += line[i].length() > 4 ? 2: line[i].length() - 1;
                    }
                }
                System.out.println(sb.toString());
            }
        }
    }
}

执行结果

      1      
    /   \    
  2       3  
 / \     / \ 
4   5   6   7
<==============深度优先遍历==============>
前序遍历: 1 2 4 5 3 6 7 
中序遍历: 4 2 5 1 6 3 7 
后序遍历: 4 5 2 6 7 3 1 
<==============广度优先便利==============>
广度遍历: 1 2 3 4 5 6 7 

相关文章

  • [算法] - 树的遍历以及优美打印

    话不多说,直接上代码 执行结果

  • 二叉树的遍历 递归 非递归 Java

    二叉树的常用遍历算法实现 前序遍历 递归实现 非递归实现(1)这个是常规思路,先遍历到根节点,并打印、压栈,然后遍...

  • 剑指offer中关于二叉树题目的总结

    关于二叉树的问题,也就是涉及二叉树的四种遍历算法以及基本的删除、插入等操作 中序遍历和前序遍历/后序遍历的结合 题...

  • 二叉树的建立 建立二叉树,利用了递归的原理,也就是在打印二叉树的前中后序遍历算法中打印结点的地方,改成了生成结点,...

  • 遍历整个 DOM 树并打印名称

    1. 遍历 DOM 树并打印节点类型及名称 2. 遍历 DOM 树并打印所有元素的 tagName 在这段代码中,...

  • BFS的分层(利用queue)

    层序遍历二叉树,并且每层换行打印 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。给定二叉树的根结点root...

  • 2018-11-19

    今天在电脑上用c语言实现了二叉树的创建,并且采用递归算法的形式进行二叉树的先序遍历和中序遍历以及后序遍历。

  • 二叉树前序中序后序遍历

    二叉树遍历方法 前序遍历:根左右。先打印,再遍历左子树,再遍历右子树; 中序遍历:左根右。先遍历左子树,再打印,再...

  • DFS(深搜)算法

    深度优先搜索算法(Depth-First-Search):是一种用于遍历或搜索树或图的算法。 沿着树的深度遍历树的...

  • 大数据面试题目

    一、数据结构与算法 1.二叉树前序、中序、后续遍历方式(递归以及非递归) 2.二叉树的深度以及广度遍历方式 ...

网友评论

      本文标题:[算法] - 树的遍历以及优美打印

      本文链接:https://www.haomeiwen.com/subject/tlvsrrtx.html