-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo654MaximumBinaryTree.java
More file actions
39 lines (32 loc) · 929 Bytes
/
No654MaximumBinaryTree.java
File metadata and controls
39 lines (32 loc) · 929 Bytes
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
package com.wzx.leetcode;
import com.wzx.entity.TreeNode;
/**
* @see <a href="https://leetcode.com/problems/maximum-binary-tree/">https://leetcode.com/problems/maximum-binary-tree/</a>
* @author wzx
*/
public class No654MaximumBinaryTree {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return recursion(nums, 0, nums.length - 1);
}
/**
* 递归
*
* time: O(n^2)
* space: O(h) 树高
*/
private TreeNode recursion(int[] nums, int begin, int end) {
if (begin == end) return new TreeNode(nums[begin]);
if (begin > end) return null;
// 找到最大值
int maxIndex = begin;
for (int i = begin; i <= end; i++) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = recursion(nums, begin, maxIndex - 1);
root.right = recursion(nums, maxIndex + 1, end);
return root;
}
}