0%

LeetCode654

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

二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。

示例 :

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

   6
 /   \   
3     5
 \    / 
  2  0   
    \
      1

提示:

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

递归建树.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
int maxId = getMaxId(nums);
int max = nums[maxId];
TreeNode node = new TreeNode(max);
if (maxId - 1 >= 0) {
node.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, maxId));
} else {
node.left = null;
}
if (maxId + 1 < nums.length) {
node.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, maxId + 1, nums.length));
} else {
node.right = null;
}
return node;
}

private int getMaxId(int[] nums) {
int maxId = 0, max = nums[0];
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
maxId = i;
max = nums[i];
}
}
return maxId;
}
}