二叉树的题,也是好久没做了。开始一直纠结着python怎么定义树结点,就打开了discussion,然后发现结点定义原题就给了。大意了大意了。然后学习了
jedihy的做法。
# 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
"""
if nums:
pos=nums.index(max(nums))
root=TreeNode(nums[pos])
root.left=self.constructMaximumBinaryTree(nums[:pos])
root.right=self.constructMaximumBinaryTree(nums[pos+1:])
return root
成功ac。