mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
@ -224,27 +224,32 @@ root->right = traversal(nums, maxValueIndex + 1, right);
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
|
||||||
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
public TreeNode constructMaximumBinaryTree(int[] nums) {
|
public TreeNode constructMaximumBinaryTree(int[] nums) {
|
||||||
if (nums.length == 0) return null;
|
return constructMaximumBinaryTree1(nums, 0, nums.length);
|
||||||
return constructMaximumBinaryTree(nums,0,nums.length);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TreeNode constructMaximumBinaryTree(int[] nums, int begin, int end) {
|
public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {
|
||||||
if (begin == end) return null;
|
if (rightIndex - leftIndex < 1) {// 没有元素了
|
||||||
|
return null;
|
||||||
int rootValue = nums[begin];
|
}
|
||||||
int index = begin;
|
if (rightIndex - leftIndex == 1) {// 只有一个元素
|
||||||
for (int i = begin; i < end ; i++) {
|
return new TreeNode(nums[leftIndex]);
|
||||||
if (nums[i] > rootValue) {
|
}
|
||||||
rootValue = nums[i];
|
int maxIndex = leftIndex;// 最大值所在位置
|
||||||
index = i;
|
int maxVal = nums[maxIndex];// 最大值
|
||||||
|
for (int i = leftIndex + 1; i < rightIndex; i++) {
|
||||||
|
if (nums[i] > maxVal){
|
||||||
|
maxVal = nums[i];
|
||||||
|
maxIndex = i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TreeNode root = new TreeNode(rootValue);
|
TreeNode root = new TreeNode(maxVal);
|
||||||
root.left = constructMaximumBinaryTree(nums, begin,index);
|
// 根据maxIndex划分左右子树
|
||||||
root.right = constructMaximumBinaryTree(nums,index+1,end);
|
root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex);
|
||||||
|
root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user