1. 题目
2. 思路
(1) 递归
- 从给定的数组区间中找出最大值建立根结点,然后递归建立左右子树即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
private int[] nums;
public TreeNode constructMaximumBinaryTree(int[] nums) {
this.nums = nums;
return recur(0, nums.length - 1);
}
private TreeNode recur(int left, int right) {
if (left > right) {
return null;
}
int maxValue = Integer.MIN_VALUE;
int maxIndex = left;
for (int i = left; i <= right; i++) {
if (nums[i] > maxValue) {
maxValue = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxValue);
root.left = recur(left, maxIndex - 1);
root.right = recur(maxIndex + 1, right);
return root;
}
}