Subthemes rule of law Leetcode -654. Maximum binary tree (Maximum Binary Tree)

Subthemes rule of law Leetcode -654. Maximum binary tree (Maximum Binary Tree)


 

Given an array of integers contain duplicate elements. Define a maximum binary tree in order to arrays constructed as follows:

  1. Binary tree root is the largest element in the array.
  2. Left subtree is constructed by the maximum value of the left part of the array the maximum binary tree.
  3. Right subtree is constructed by the maximum value of the right part of the array the maximum binary tree.

Construction of the binary tree by the maximum given array, and outputs the root of this tree.

 

Example:

Input: [3,2,1,6,0,5] 
Output: Returns this tree below the root node: 

      6 
    / \ 
   35 
    \ / 
     20    
       \ 
        1

 

prompt:

  1. Given the size of the array between [1, 1000].

 

L, respectively, to find the maximum value in the interval r, then the left and right subtree structure ok.

/**
 * 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 buildTreeNode(nums,0,nums.length-1);
    }
    
    public TreeNode buildTreeNode(int[] nums,int l,int r){
        if(l>r){
            return null;
        }
        int index = -1;
        int max = Integer.MIN_VALUE;
        for(int i=l;i<=r;i++){
            if(nums[i]>max){
                max = nums[i];
                index = i;
            }
        }
        TreeNode res = new TreeNode(max);
        res.left = buildTreeNode(nums,l,index-1);
        res.right = buildTreeNode(nums,index+1,r);
        return res;
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11515743.html