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

13 篇文章 0 订阅
3 篇文章 0 订阅

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

  • 时间复杂度:数组元素个数为 n n ,最大二叉树平均有log(n)层,在每一层都需要遍历数组找到最大的那个元素,时间复杂度为 O(n) O ( n ) ,因此平均时间复杂度为 O(nlog(n)) O ( n l o g ( n ) ) 。考虑最坏的情况,数组元素已经按照从小到大的顺序排好,则最大二叉树总共有 n n 层,每一层遍历找最大元素的时间复杂度是O(n),因此总的时间复杂度为 O(n2) O ( n 2 )
  • 空间复杂度:算法是在原数组上操作,并没有增加额外的空间,因此空间复杂度为 O(n) O ( n )
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值