Description
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.
Example:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
Solution
可以直接在原数组上操作,构造树结构一般考虑递归,代码如下:
class TreeNode{
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
public class MaxBinaryTree {
public TreeNode contructMaximumBinaryTree(int[] nums){
return construct(nums, 0, nums.length);
}
/**
* 使用下标方式在原数组上操作,递归方式构造
* @param nums
* @param start
* @param end
* @return
*/
private TreeNode construct(int[] nums, int start, int end){
if (start == end){
return null;
}
int maxNumPos = findNumMaxPos(nums, start, end);
TreeNode root = new TreeNode(nums[maxNumPos]);
root.left = construct(nums, start, maxNumPos);
root.right = construct(nums, maxNumPos + 1, end);
return root;
}
/**
* 获取数组start和end区间最大值的索引
* @param nums
* @param start
* @param end
* @return
*/
private int findNumMaxPos(int[] nums, int start, int end){
int maxNumPos = start;
for (int i = start; i < end; i++){
if (nums[i] > nums[maxNumPos]){
maxNumPos = i;
}
}
return maxNumPos;
}
public static void main(String[] args) {
int[] testArray = new int[]{68, 72, 12, 54, 90, 19, 6};
System.out.println(new MaxBinaryTree().contructMaximumBinaryTree(testArray));
}
}
Complexity Analysis
- 时间复杂度:数组元素个数为 n n ,最大二叉树平均有层,在每一层都需要遍历数组找到最大的那个元素,时间复杂度为 O(n) O ( n ) ,因此平均时间复杂度为 O(nlog(n)) O ( n l o g ( n ) ) 。考虑最坏的情况,数组元素已经按照从小到大的顺序排好,则最大二叉树总共有 n n 层,每一层遍历找最大元素的时间复杂度是,因此总的时间复杂度为 O(n2) O ( n 2 ) 。
- 空间复杂度:算法是在原数组上操作,并没有增加额外的空间,因此空间复杂度为 O(n) O ( n )