力扣Java必备工具类

问题

每次刷题都是用Java,在构建树和链表的时候十分不方便,因为官方给的数据一般就是一个数组,所以自己在idea调试很麻烦,像这样
在这里插入图片描述

解决

需求:

  • 数组中序构造二叉树
  • 美化输出二叉树(toString)
  • 数组转链表
  • 美化输出链表

工具类:

import java.util.LinkedList;

/**
* @Description: 二叉树类
* @Param:
* @return:
* @Author: leftHand
* @Date: 2022-08-12
*/
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    TreeNode(int x, TreeNode left, TreeNode right) {
        val = x;
        this.left = left;
        this.right = right;
    }

    /**
     * 获取二叉树深度
     */
    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 String showTree(TreeNode root) {
        StringBuilder result = new StringBuilder();
        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;
                }
            }
            result.append(sb).append("\n");
        }
        return result.toString();
    }

    /**
     * 数组层序构造二叉树
     */
    public static TreeNode arrayToBTree(Integer[] arrs) {
        if (arrs == null || arrs.length == 0) {
            return null;
        }
        TreeNode head = new TreeNode(arrs[0]);
        TreeNode node;
        LinkedList<TreeNode> q = new LinkedList<>();
        q.add(head);

        int index = 1;
        while (!q.isEmpty()) {
            for (int i = 0; i < q.size(); i++) {
                node = q.poll();
                if (node != null) {
                    if (index < arrs.length) {
                        TreeNode left = arrs[index] == null ? null : new TreeNode(arrs[index]);
                        index++;
                        node.left = left;
                        q.add(left);
                    }
                    if (index < arrs.length) {
                        TreeNode right = arrs[index] == null ? null : new TreeNode(arrs[index]);
                        index++;
                        node.right = right;
                        q.add(right);
                    }
                }

            }
        }
        return head;
    }

    @Override
    public String toString() {
        return showTree(this);
    }
}
/**
* @Description: 单链表类
* @Param:
* @return:
* @Author: leftHand
* @Date: 2022-08-12
*/
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
    ListNode(int x, ListNode next) {
        val = x;
        this.next = next;
    }

    public ListNode() {

    }

    public static ListNode createList(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]), node = head;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == null) {
                throw new RuntimeException("链表中间节点不能为空: " + head);
            }
            node.next = new ListNode(arr[i]);
            node = node.next;
        }
        return head;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.val).append(" -> ").append(this.next == null? "null": this.next);
        return sb.toString();
    }
}

/**
 * 带随机节点的链表
 * */
class Node extends ListNode {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        super();
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

/**
 * @program: leetcode
 * @description: 算法构造工具
 * @author: LeftHand
 * @create: 2022-08-12 11:25
 **/
public class MyUtils {
    /**
     * 层次构造二叉树
     */
    public static TreeNode createTreeByLevelOrderArr(Integer[] arr) {
        return TreeNode.arrayToBTree(arr);
    }
    /**
     * 构造单向链表
     * */
    public static ListNode createListNodeByArr(Integer[] arr) {
        return ListNode.createList(arr);
    }

    public static void main(String[] args) {
        // 构造一棵树,并美化输出
        TreeNode treeNode = MyUtils.createTreeByLevelOrderArr(new Integer[]{1, 3, null, 3, 2, null});
        System.out.println(treeNode);

        // 构造一个单链表,并美化输出
        ListNode listNode = MyUtils.createListNodeByArr(new Integer[]{1, 1, 6, 3});
        System.out.println(listNode);


    }
}

效果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左手八嘎呀路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值