-
Notifications
You must be signed in to change notification settings - Fork 0
/
654.最大二叉树.java
57 lines (53 loc) · 1.4 KB
/
654.最大二叉树.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode.cn id=654 lang=java
*
* [654] 最大二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public 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 {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return traverse(nums, 0, nums.length - 1);
}
private TreeNode traverse(int[] nums, int start, int end) {
if (end < start)
return null;
// 获取最大值的key、value
int[] values = getMaxKeyVal(nums, start, end);
int max = values[0];
int index = values[1];
// 递归处理左右节点
TreeNode left = traverse(nums, start, index - 1);
TreeNode right = traverse(nums, index + 1, end);
TreeNode node = new TreeNode(max);
node.left = left;
node.right = right;
return node;
}
private int[] getMaxKeyVal(int[] nums, int start, int end) {
int max = Integer.MIN_VALUE;
int index = 0;
for (int i = start; i <= end; i++) {
if (nums[i] > max) {
max = nums[i];
index = i;
}
}
return new int[] { max, index };
}
}
// @lc code=end