LeetCode刷题助手:根据数组生成二叉树

本文介绍了一种将LeetCode中数组形式的二叉树数据转换为二叉树对象的方法,便于在本地IDE进行调试。通过定义二叉树节点和转换函数,实现了数组到二叉树的自动化转换,简化了解题过程。提供的测试代码可帮助验证转换效果,但可能需要根据实际使用情况进行调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家在刷LeetCode的二叉树相关的题目的时候,遇到问题需要在本地IDE里调试的时候,题目里给的二叉树的形式是一个数组,类似

Integer[] array = new Integer[]{1, null, 2, null, null, null, 3};

这种形式,它是以null来做填充,构成一个完全二叉树,具体的图我就不画了,大家自己理解一下。而我们需要自己手动把它转换成二叉树的形式,再把这个二叉树作为参数来进行解题。

因为感觉这样做十分的麻烦,所以我写了一个转换方法,可以把上面这种类型的数组自动转化为一个二叉树。

首先定义二叉树节点:

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

转换方法如下:

    public static TreeNode convert(Integer[] array) {
        int floor = 0, count = 0;
        TreeNode[] treeNodes = new TreeNode[array.length];
        while (array != null && count < array.length) {
            int start = (int) Math.pow(2, floor) - 1;
            int end = (int) Math.pow(2, floor + 1) - 1;
            if (end > array.length) {
                end = array.length;
            }
            for (int i = start; i < end; i++) {
                if (array[i] != null) {
                    treeNodes[i] = new TreeNode(array[i]);
                } else {
                    treeNodes[i] = null;
                }
                if (i > 0) {
                    int parent = (i - 1) / 2;
                    if (parent >= 0) {
                        TreeNode pNode = treeNodes[parent];
                        if (pNode != null) {
                            if (i % 2 == 1) {
                                pNode.left = treeNodes[i];
                            } else {
                                pNode.right = treeNodes[i];
                            }
                        }
                    }
                }
                count++;
            }
            floor++;
        }
        return treeNodes[0];
    }

测试代码:

    public static void main(String[] args) {
        Integer[] array = new Integer[]{1, null, 2, null, null, null, 3};
        TreeNode root = convert(array);

    }

用debug查看结果:

我没有写特别多的测试用例,所以用的时候如果有问题,麻烦自己调试修改一下。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值