-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0654-MaximumBinaryTree.cs
37 lines (31 loc) · 1.15 KB
/
0654-MaximumBinaryTree.cs
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
//-----------------------------------------------------------------------------
// Runtime: 116ms
// Memory Usage: 28 MB
// Link: https://leetcode.com/submissions/detail/262177117/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0654_MaximumBinaryTree
{
public TreeNode ConstructMaximumBinaryTree(int[] nums)
{
return ConstructMaximumBinaryTree(nums, 0, nums.Length);
}
private TreeNode ConstructMaximumBinaryTree(int[] nums, int left, int right)
{
if (left == right) return null;
var maxIndex = GetMaxIndex(nums, left, right);
var node = new TreeNode(nums[maxIndex]);
node.left = ConstructMaximumBinaryTree(nums, left, maxIndex);
node.right = ConstructMaximumBinaryTree(nums, maxIndex + 1, right);
return node;
}
private int GetMaxIndex(int[] nums, int left, int right)
{
var result = left;
for (int i = left; i < right; i++)
if (nums[result] < nums[i]) result = i;
return result;
}
}
}