领扣LintCode算法问题答案-1106. 最大二叉树
1106. 最大二叉树
描述
给定一个没有重复元素的整数数组。根据此数组构建的最大二叉树定义如下:
- root是数组中的最大数字。
- 左子树是根据最大数字左侧的子数组构建的最大二叉树。
- 右子树是根据最大数字右侧的子数组构建的最大二叉树。
通过给定的数组构造最大二叉树并返回此树的根节点。
给定的数组的大小范围为 [1,1000]。
样例 1:
输入: {3,2,1,6,0,5}
输出: 返回代表下面这棵树的根节点:
6
/ \
3 5
\ /
2 0
\
1
样例 2:
输入: {1,2,3,4}
输出: 返回代表下面这棵树的根节点:
4
/
3
/
2
/
1
题解
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param nums: an array
* @return: the maximum tree
*/
public TreeNode constructMaximumBinaryTree(int[] nums) {
// Write your code here
TreeNode root = constructMaximumBinaryTree(nums, 0, nums.length - 1);
return root;
}
private TreeNode constructMaximumBinaryTree(int[] nums, int startIndex, int endIndex) {
// Write your code here
if (endIndex < startIndex) {
return null;
}
int maxIndex = startIndex;
for (int i = startIndex + 1; i <= endIndex; i++) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = constructMaximumBinaryTree(nums, startIndex, maxIndex - 1);
root.right = constructMaximumBinaryTree(nums, maxIndex + 1, endIndex);
return root;
}
}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。