leetcode链表树构造工具类

刷leetcode有时候代码看不懂要debug,但是有些结构不好构造,比如链表、树,之前写了点工具类,拿出来分享分享

链表

创建单链表、打印单链表

/**
 * 操作链表工具类
 *
 * @author lastwhisper
 * @date 1/7/2020
 */
public class LinkedListUtil {

    /**
     * 创建单链表
     */
    public static ListNode createListNode(int... arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    /**
     * 打印单链表
     */
    public static void printListNode(String msg, ListNode head) {
        System.out.println(msg + appendVal(head));
    }

    /**
     * 打印单链表
     */
    public static void printListNode(ListNode head) {
        System.out.println(appendVal(head));
    }

    private static String appendVal(ListNode head) {
        StringBuilder sb = new StringBuilder();
        ListNode current = head;
        while (current != null) {
            sb.append(current.val);
            sb.append("->");
            current = current.next;
        }
        sb.append("NULL");
        return sb.toString();
    }


    public static void main(String[] args) {
        printListNode(createListNode(1, 2, 3, 4, 5, 6, 7));
    }
}

创建树,打印树


/**
 * 树相关工具类
 * @author lastwhisper
 * @date 1/16/2020
 */
public class TreeUtil {

    /**
     * 根据数组创建二叉树
     *  一、[5,4,8,11,null,13,4,7,2,null,null,null,1]
     *               5
     *              / \
     *             4   8
     *            /   / \
     *           11  13  4
     *          /  \      \
     *         7    2      1
     * 二、[1,null,2,3]
     *            1
     *             \
     *              2
     *             /
     *            3
     * 参考 https://blog.csdn.net/lenfranky/article/details/84444816
     * @param array 数组
     */
    public static TreeNode createTree(Integer... array) {
        if (array.length == 0) return new TreeNode(0);
        Deque<TreeNode> nodeQueue = new LinkedList<>();
        // 创建一个根节点
        TreeNode root = new TreeNode(array[0]);
        nodeQueue.offer(root);
        TreeNode current;
        // 记录当前行节点的数量(注意不一定是2的幂,而是上一行中非空节点的数量乘2)
        int lineNodeNum = 2;
        // 记录当前行中数字在数组中的开始位置
        int startIndex = 1;
        // 记录数组中剩余的元素的数量
        int restLength = array.length - 1;

        while (restLength > 0) {
            // 只有最后一行可以不满,其余行必须是满的
//            // 若输入的数组的数量是错误的,直接跳出程序
//            if (restLength < lineNodeNum) {
//                System.out.println("Wrong Input!");
//                return new TreeNode(0);
//            }
            for (int i = startIndex; i < startIndex + lineNodeNum; i = i + 2) {
                // 说明已经将nums中的数字用完,此时应停止遍历,并可以直接返回root
                if (i == array.length) return root;
                current = nodeQueue.poll();
                if (array[i] != null) {
                    current.left = new TreeNode(array[i]);
                    nodeQueue.offer(current.left);
                }
                // 同上,说明已经将nums中的数字用完,此时应停止遍历,并可以直接返回root
                if (i + 1 == array.length) return root;
                if (array[i + 1] != null) {
                    current.right = new TreeNode(array[i + 1]);
                    nodeQueue.offer(current.right);
                }
            }
            startIndex += lineNodeNum;
            restLength -= lineNodeNum;
            lineNodeNum = nodeQueue.size() * 2;
        }

        return root;
    }

    /**
     * 二叉树层次遍历
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)
            return result;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            // 遍历每层的数据
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size > 0) {
                root = queue.poll();
                list.add(root.val);
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
                size--;
            }
            result.add(list);
        }
        return result;
    }

    /**
     * 输出二叉树层次遍历的结果
     */
    public static void printLevelOrder(TreeNode root) {
        PrintUtil.printLists(levelOrder(root));
    }

    public static void main(String[] args) {
//        printLevelOrder(createTree(1, null, 2, 3));
        printLevelOrder(createTree(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1));
        //printLevelOrder(createTree(1,2,3,null,4,5,null));
    }
}

打印工具类

/**
 * 打印工具类
 * @author lastwhisper
 * @date 2020/2/1
 */
public class PrintUtil {

    /**
     * 层次打印二维数组
     */
    public static void printLists(List<List<Integer>> lists) {
        System.out.println("[");
        int counter1 = 1;
        for (List<Integer> list : lists) {
            System.out.print("\t[\"");
            int counter2 = 1;
            for (Integer i : list) {
                if (counter2 != list.size()) {
                    System.out.print(i + "\",\"");
                } else {
                    System.out.print(i);
                }
                counter2++;
            }
            if (counter1 != lists.size()) {
                System.out.print("\"],\n");
            } else {
                System.out.print("\"]\n");
            }
            counter1++;
        }
        System.out.println("]");
    }

    public static void printStringLists(List<List<String>> lists) {
        System.out.println("[");
        int counter1 = 1;
        for (List<String> list : lists) {
            System.out.print("\t[\"");
            int counter2 = 1;
            for (String i : list) {
                if (counter2 != list.size()) {
                    System.out.print(i + "\",\"");
                } else {
                    System.out.print(i );
                }
                counter2++;
            }
            if (counter1 != lists.size()) {
                System.out.print("\"],\n");
            } else {
                System.out.print("\"]\n");
            }
            counter1++;
        }
        System.out.println("]");
    }

    /**
     * 打印数组
     */
    public static void printList(Collection<?> collection) {
        System.out.println(collection2String(collection));
    }

    /**
     * 将Collection扁平化迭代成String
     */
    public static String collection2String(Collection<?> collection) {
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("[\"");
            int counter = 1;
            for (Object object : collection) {
                sb.append(object);
                if (counter != collection.size()) {
                    sb.append("\",\"");
                }
                counter++;
            }
            sb.append("\"]");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值