링크
preorder, inorder 로 쓰여진 배열을 보고 bst 를 만드는 문제
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
left = right = None
num = len(preorder)
if num == 0: return left
root = TreeNode(preorder[0])
if num == 1: return root
elif num == 2:
if preorder == inorder:
right = TreeNode(preorder[1])
else:
left = TreeNode(preorder[1])
else:
rootIdx = inorder.index(root.val)
left = self.buildTree(preorder[1:rootIdx + 1], inorder[:rootIdx])
right = self.buildTree(preorder[rootIdx+1:], inorder[rootIdx+1:])
root.left = left
root.right = right
return root
class Solution:
def buildTree(self, preorder, inorder):
def build(stop):
if inorder and inorder[-1] != stop:
root = TreeNode(preorder.pop())
root.left = build(root.val)
inorder.pop()
root.right = build(stop)
return root
preorder.reverse()
inorder.reverse()
return build(None)