这题挺简单的,一眼看上去知道使用递归,主要就是找到最大值,然后根据最大值将list分成两部分,然后递归地进行构造树。主要学习python关于树的相关语法(太习惯c++,emmmmm)。
note:
python当中没有null,只有None.
python有一个Treecode结构,通过 root = Treecode(num)来构造,通过root.left, root.right来构造左右分支。
python类内的递归调用,要加self.function(表明它是这个当前类中的函数,否则会出现NameError,not defined)
附代码
class Solution:
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return None
else:
index = 0
for i in range(len(nums)):
if nums[i] > nums[index]:
index = i
root = TreeNode(nums[index])
left = nums[0:index]
right = nums[index+1:]
root.left = self.constructMaximumBinaryTree(left)
root.right = self.constructMaximumBinaryTree(right)
return root