力扣 LeetCode 654. 最大二叉树(Day9:二叉树)
解题思路:
构造二叉树一定要用前序
中左右,先有中间节点,才有左右节点
区间左闭右开
注意递归终止条件
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return buildHelper(nums, 0, nums.length);
}
public TreeNode buildHelper(int[] nums, int start, int end) {
if (end - start < 1) return null;
if (end - start == 1) return new TreeNode(nums[start]);
int max = 0;
int index = 0;
for (int i = start; i < end; i++) {
if (max < nums[i]) {
max = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(max);
root.left = buildHelper(nums, start, index);
root.right = buildHelper(nums, index + 1, end);
return root;
}
}