2019年3月12日 1008. Construct Binary Search Tree from Preorder Traversal

树的转换,一道新题,部分递归的条件判断不是很清晰,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
posted @ 2019-03-12 13:56  miuc  阅读(117)  评论(0编辑  收藏  举报