树的转换,一道新题,部分递归的条件判断不是很清晰,WA了一次。
# 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 bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if len(preorder) == 0: return None root = TreeNode(preorder[0]) m = False for idx, v in enumerate(preorder[1:]): if v > preorder[0]: root.left = self.bstFromPreorder(preorder[1:idx+1]) root.right = self.bstFromPreorder(preorder[idx+1:]) m = True break if m == False: root.left = self.bstFromPreorder(preorder[1:]) return root