654. 最大二叉树

深度优先搜索

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {

        return buildSonTree(nums, 0, nums.length);
    }

    /**
     * 左闭右开区间
     * 先找到数组的最大值,作为根节点,然后将数组一分为二,继续递归分割
     */
    public TreeNode buildSonTree(int[] nums, int left, int right){

        /**
         * 如果数组为空,或者只有一个元素,则该节点就是根节点
         */
        if (right - left == 0){
            return null;
        }

        if (right - left == 1){
            return new TreeNode(nums[left]);
        }

        /**
         * 记录下根节点的位置
         */
        int index = left;

        for (int i = left; i < right; i++) {

            if (nums[i] > nums[index]){
                index = i;
            }
        }

        /**
         * 传入新的数组边界,继续分割
         */
        TreeNode root = new TreeNode(nums[index]);

        root.left = buildSonTree(nums, left, index);
        root.right = buildSonTree(nums, index + 1, right);

        return root;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/maximum-binary-tree/

posted @ 2022-02-22 21:27  振袖秋枫问红叶  阅读(28)  评论(0)    收藏  举报