Leetcod刷题(16)—— 110. 平衡二叉树

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

二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。

示例 :

输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

提示:
给定的数组的大小在 [1, 1000] 之间。

解决思路:
1.遍历一次,先求出数组中的最大值index,创建root,值为nums[index]
2.index左边的数组,再次递归进行一次操作,为root的左子树
3.index右边的数组,也是递归,作为root的右子树
4.跳出递归的条件即为start>end

class Solution {
      public static TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return constructMaximumBinaryTreeSub(nums, 0, nums.length - 1);
    }

    public static TreeNode constructMaximumBinaryTreeSub(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        int maxIndex = getMaxIndex(start, end, nums);
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = constructMaximumBinaryTreeSub(nums, start, maxIndex - 1);
        root.right = constructMaximumBinaryTreeSub(nums, maxIndex + 1, end);
        return root;
    }

    public static int getMaxIndex(int start, int end, int[] nums) {
        int maxIndex = start;
        for (int i = start + 1; i <= end; i++) {
            int val = nums[i];
            int maxVal = nums[maxIndex];
            if (val > maxVal) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}
发布了204 篇原创文章 · 获赞 684 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/u012124438/article/details/102621826
今日推荐