654.最大二叉树
思路:
中序遍历,将最大值放在中间节点,在根据要求在不同区间内寻找其左右节点。
代码:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return process(nums, 0, nums.length);
}
private TreeNode process(int[] nums, int start, int end){
if(end - start < 1) return null;
if(end - start == 1) return new TreeNode(nums[start]);
TreeNode root = new TreeNode();
int maxindex = start;
int max = nums[maxindex];
for(int i = start + 1; i < end; i++){
if(nums[i] > max){
maxindex = i;
max = nums[maxindex];
}
}
root.val = max;