Leetcode 654.最大二叉树

题目链接

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

题目描述

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

1. 二叉树的根是数组中的最大元素。
2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

Example 1:

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

      6
    /   
   3     5
        / 
     2  0   
       
        1

注意:

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

题解

采用递归的方式来解决。每次找出当前数组的最大值,作为根节点。根节点左边的是左子树,右边的是右子树;采用递归的方式构造,就可以得出最后的结果。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        
        return constructMaximumBinaryTree(nums, 0, nums.length - 1);
    }
    
    public TreeNode constructMaximumBinaryTree(int[] a, int left, int right) {
        if (left > right) { return null; }
        int val = findMax(a, left, right);
        TreeNode root = new TreeNode(a[val]);
        root.left = constructMaximumBinaryTree(a, left, val - 1);
        root.right = constructMaximumBinaryTree(a, val + 1, right);
        return root;
    }
    
    /**
    * 返回最大元素的下标
    **/
    public int findMax(int[] a, int left, int right) {
        if (left == right) {
            return left;
        }
        int max = a[left];
        int ant = left;
        for (int i = left + 1; i <= right; i++) {
            if (a[i] > max) { 
                max = a[i];
                ant = i;
            }
        }
        return ant;
    }
}
原文地址:https://www.cnblogs.com/xiagnming/p/9540388.html