LeetCode--最大二叉树

本文介绍了一种构建最大二叉树的算法,通过寻找数组中的最大值作为根节点,然后递归地构建左右子树。文章详细解释了算法的实现过程,包括查找最大值及其索引的方法,以及如何通过递归调用构造左右子树。

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

题目描述:
在这里插入图片描述
解题思路:以数组中最大值为中心,分为左右两段,再递归遍历左右两段,注意避免空指针与空数组。

class Solution {
    public static TreeNode constructMaximumBinaryTree(int[] nums) {
        int [] shuju = new int[2];    //定义数组shuju
        shuju = findMaxindex(nums);
        if(shuju[0] < 0){
            return null;
        }
        int [] leftNums = new int[shuju[0]];
        for(int j=0; j < shuju[0]; j++){
            leftNums[j] = nums[j];
        }
        int [] rightNums = new int[nums.length - shuju[0]-1];
        for(int j = 0;j < nums.length - shuju[0]-1 ;j++){
            rightNums[j] = nums[shuju[0]+j+1];
        }
        TreeNode node = new TreeNode(nums[shuju[0]]);      //创建节点
        node.val = shuju[1];    //将数组最大值赋值给该节点
        node.left = constructMaximumBinaryTree(leftNums);  //递归创建该节点左子节点
        node.right = constructMaximumBinaryTree(rightNums);  //递归创建该节点右子节点
        return  node;
    }
    public static int[] findMaxindex(int[] nums){     //数组中第一个数为最大值的索引,第二个值为最大值
        int [] shuju = new int[2];
        int index = -1;
        if(nums.length == 0){
            shuju[0] = -1;
            shuju[1] = -1;
            return shuju;
        }
        else {
            int max = nums[0];
            for(int i=0; i < nums.length;i++){
                if(max <= nums[i]){
                    max = nums[i];
                    shuju[0] = i;
                    shuju[1] = max;
                }
            }
            return shuju;  
        }


    }
    public  static void midPreOrder(TreeNode node){     //中序遍历
        if(node == null){
            return ;
        }
        midPreOrder(node.left);
        System.out.println("data is " + node.val);
        midPreOrder(node.right);

    }

    public static void main(String [] args){
        int [] Nums = new int[]{3,2,1,6,0,5};
        TreeNode newTree = null;
        newTree = constructMaximumBinaryTree(Nums);   //创建一颗最大二叉树
        midPreOrder(newTree);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值