# Definition for a binary tree node.
importcollectionsfromtypingimportOptional,ListclassTreeNode:def__init__(self,val=0,left=None,right=None):self.val=valself.left=leftself.right=rightclassSolution:# ์ฃผ์ด์ง inorder, preorder ๊ฐ์ผ๋ก ํธ๋ฆฌ ๋ง๋๋ ๋ฌธ์
defbuildTree(self,preorder:List[int],inorder:List[int])->Optional[TreeNode]:ifnotinorder:returnNone# preorder ALWAYS has the node first.
# But you don't know the size of either branch.
pre_popleft=preorder.pop(0)# pre_popleft = collections.deque(preorder).popleft()
# inorder ALWAYS has the left branch to the left of the node
# and right branch to the right of the node.
# So now you know the size of each branch.
index=0forxininorder:ifx==pre_popleft:breakindex+=1node=TreeNode(inorder[index])node.left=self.buildTree(preorder,inorder[:index])node.right=self.buildTree(preorder,inorder[index+1:])returnnode
Leave a comment