-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_binary_tree.py
More file actions
33 lines (29 loc) · 889 Bytes
/
maximum_binary_tree.py
File metadata and controls
33 lines (29 loc) · 889 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def f(l, r):
if l > r:
return None
index, maximum = self.find_max(nums, l, r)
node = TreeNode(maximum)
node.left = f(l, index-1)
node.right = f(index+1, r)
return node
return f(0, len(nums)-1)
def find_max(self, nums, l, r):
maximum = float('-inf')
index = None
for i in range(l, r+1):
if nums[i] > maximum:
maximum = nums[i]
index = i
return (index, maximum)