其他分享
首页 > 其他分享> > 【LeetCode】654. 最大二叉树

【LeetCode】654. 最大二叉树

作者:互联网

题目描述:

给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:

解题思路:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums, 0, nums.length);
    }

    //递归构建二叉树
    public TreeNode construct(int[] nums, int left, int right) {
        if (left == right) return null;
        int maxIndex = max(nums, left, right);
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = construct(nums, left, maxIndex);
        root.right = construct(nums, maxIndex + 1, right);
        return root;
    }

    //找到数组中最大值的下标
    public int max(int[] nums, int left, int right) {
        int maxIndex = left;
        for (int i = left; i < right; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}

标签:right,TreeNode,nums,int,最大值,654,二叉树,LeetCode,left
来源: https://blog.csdn.net/weixin_43356538/article/details/114412084