Leetcode学习笔记:#654. Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
实现:
public TreeNode constructMaximumBinaryTree(int[] nums){
if(nums == null) return null;
return buildTree(nums, 0, nums.length-1);
}
public buildTree(int[] nums, int start, int end){
if(start > end) return null;
int indexMax = start;
for(int i = start + 1; i <= end; i++){
if(nums[i] > nums[indexMax]){
indexMax = i;
}
}
TreeNode root = new TreeNode(nums[indexMax]);
root.left = buildTree(nums, start, indexMax-1);
root.right = buildTree(nums, indexMax+1, end);
return root;
}
思路:
中序遍历,递归。每次递归把数组中的最大值作为根节点,复杂度与快速排序相似。