Участник:Ковальков Антон М05-903б/Construct Binary Search Tree from Preorder Traversal

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/

Python3

class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if len(preorder) == 0:
            return None
        if len(preorder) == 1:
            return TreeNode(preorder[0])
        root_val = preorder[0]
        root = TreeNode(root_val)
        left = self.bstFromPreorder([v for v in preorder if v < root_val])
        right = self.bstFromPreorder([v for v in preorder if v > root_val])
        root.left = left
        root.right = right
        return root