-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
28 lines (24 loc) · 788 Bytes
/
solution.py
File metadata and controls
28 lines (24 loc) · 788 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
# 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
"""
return self.build(nums, 0, len(nums) - 1)
def build(self, nums, beg, end):
if beg > end:
return None
max_index = beg
for i in xrange(beg, end + 1):
if nums[i] > nums[max_index]:
max_index = i
root = TreeNode(nums[max_index])
root.left = self.build(nums, beg, max_index - 1)
root.right = self.build(nums, max_index + 1, end)
return root