[leetcode] 654: 构造最大二叉树

本文介绍了一种在给定无重复整数数组的基础上构建最大二叉树的方法。通过递归方式,每次选择数组中的最大值作为当前层级的根节点,并以此划分左右子树继续构建。文章提供了完整的Java实现代码,并分析了该算法的时间复杂度和空间复杂度。

Description

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Example:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
最大二叉树

Solution

可以直接在原数组上操作,构造树结构一般考虑递归,代码如下:

class TreeNode{
    int value;
    TreeNode left;
    TreeNode right;

    public TreeNode(int value) {
        this.value = value;
    }
}

public class MaxBinaryTree {
    public TreeNode contructMaximumBinaryTree(int[] nums){
        return construct(nums, 0, nums.length);
    }

    /**
     *  使用下标方式在原数组上操作,递归方式构造
     * @param nums
     * @param start
     * @param end
     * @return
     */
    private TreeNode construct(int[] nums, int start, int end){
        if (start == end){
            return null;
        }

        int maxNumPos = findNumMaxPos(nums, start, end);
        TreeNode root = new TreeNode(nums[maxNumPos]);
        root.left = construct(nums, start, maxNumPos);
        root.right = construct(nums, maxNumPos + 1, end);

        return root;
    }

    /**
     * 获取数组start和end区间最大值的索引
     * @param nums
     * @param start
     * @param end
     * @return
     */
    private int findNumMaxPos(int[] nums, int start, int end){
        int maxNumPos = start;
        for (int i = start; i < end; i++){
            if (nums[i] > nums[maxNumPos]){
                maxNumPos = i;
            }
        }

        return maxNumPos;
    }

    public static void main(String[] args) {
        int[] testArray = new int[]{68, 72, 12, 54, 90, 19, 6};

        System.out.println(new MaxBinaryTree().contructMaximumBinaryTree(testArray));
    }
}

Complexity Analysis

  • 时间复杂度:数组元素个数为nn,最大二叉树平均有log(n)层,在每一层都需要遍历数组找到最大的那个元素,时间复杂度为O(n)O(n),因此平均时间复杂度为O(nlog(n))O(nlog(n))。考虑最坏的情况,数组元素已经按照从小到大的顺序排好,则最大二叉树总共有nn层,每一层遍历找最大元素的时间复杂度是O(n),因此总的时间复杂度为O(n2)O(n2)
  • 空间复杂度:算法是在原数组上操作,并没有增加额外的空间,因此空间复杂度为O(n)O(n)
### 题目分析 Leetcode 654最大二叉树要求根据给定的不含重复元素的整数数组构建最大二叉树,其规则为:二叉树的根是数组中的最大元素,左子树是通过数组中最大值左边部分构造出的最大二叉树,右子树是通过数组中最大值右边部分构造出的最大二叉树[^4]。 ### 解题思路分析 - **递归法**:解决此问题的核心思路是递归。先在当前数组区间内找到最大值及其索引,将最大值作为当前根节点,再分别对最大值左边和右边的子数组递归构建左右子树。 - **避免新数组构造**:在构造过程中,为节约时间和空间开销,不建议每次分隔时定义新的数组,而是通过下标索引直接在原数组上操作。 ### 代码实现分析 #### Java代码 ```java class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { return build(nums, 0, nums.length - 1); } TreeNode build(int[] nums, int lo, int high) { if (lo > high) { return null; } int index = -1; int maxValue = Integer.MIN_VALUE; for (int i = lo; i <= high; i++) { if (nums[i] > maxValue) { index = i; maxValue = nums[i]; } } TreeNode root = new TreeNode(maxValue); root.left = build(nums, lo, index - 1); root.right = build(nums, index + 1, high); return root; } } ``` 此Java代码通过`constructMaximumBinaryTree`方法调用`build`方法开始构建最大二叉树。`build`方法在指定区间`[lo, high]`内找到最大值及其索引,创建根节点,递归构建左右子树[^1]。 #### Python代码 ```python class Solution: """最大二叉树 递归法""" def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: return self.traversal(nums, 0, len(nums)) def traversal(self, nums: List[int], begin: int, end: int) -> TreeNode: # 列表长度为0时返回空节点 if begin == end: return None # 找到最大的值和其对应的下标 max_index = begin for i in range(begin, end): if nums[i] > nums[max_index]: max_index = i # 构建当前节点 root = TreeNode(nums[max_index]) # 递归构建左右子树 root.left = self.traversal(nums, begin, max_index) root.right = self.traversal(nums, max_index + 1, end) return root ``` Python代码中,`constructMaximumBinaryTree`方法调用`traversal`方法,`traversal`方法在指定区间`[begin, end)`内找到最大值及其索引,创建根节点并递归构建左右子树。避免了创建新数组,直接通过下标操作原数组,节约了空间和时间[^2]。 #### C++代码 ```cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return build(nums, 0, nums.size()); } private: // 构造[l, r)范围的最大二叉树 TreeNode* build(const vector<int>& nums, int l, int r) { if (l == r) return nullptr; // 找出[l, r)范围内最大值及索引 int maxVal = nums[l], maxIdx = l; for (int i = l + 1; i < r; i++) { if (nums[i] > maxVal) { maxVal = nums[i]; maxIdx = i; } } TreeNode* root = new TreeNode(maxVal); root->left = build(nums, l, maxIdx); root->right = build(nums, maxIdx + 1, r); return root; } }; ``` C++代码同样采用递归方法,`constructMaximumBinaryTree`方法调用`build`方法,在指定区间`[l, r)`内找到最大值及其索引,创建根节点并递归构建左右子树[^3]。 ### 总结 - **递归是关键**:递归是解决最大二叉树问题的有效方法,通过不断在子数组中找最大值构建子树,最终完成整棵树的构建。 - **优化策略**:在构造二叉树时,使用下标索引操作原数组,避免创建新数组,能有效节约时间和空间开销。 - **通用性**:此递归构建思路可应用于其他类似用数组构造二叉树的题目。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值