[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal (Python)
python, algorithms, array, hash-table, divide-and-conquer, tree, binary-tree
Tags: algorithms, array, binary-tree, divide-and-conquer, hash-table, python, tree
Categories: LeetCode
- index ν¨μλ₯Ό μ¬μ©ν΄λ λ¨
collections.deque(preorder).popleft()λ₯Ό μ¬μ©νμ΄μ κ³μ μ€λ₯κ° λ°μνλ κ±°μμ- μ΄λ λ°λ‘ λ΄μ₯ ν¨μλ₯Ό λ§λ€μ΄μ dequeλ₯Ό λμμ£Όκ²λ νλ λ°©μμΌλ‘ ν΄κ²°ν μ μμ
- μ΄ μμ κ³μ μλ‘μ΄ dequeλ₯Ό λ§λ λ€λ κ²
Solution
# Definition for a binary tree node.
import collections
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# μ£Όμ΄μ§ inorder, preorder κ°μΌλ‘ νΈλ¦¬ λ§λλ λ¬Έμ
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not inorder:
return None
# 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 = 0
for x in inorder:
if x == pre_popleft:
break
index += 1
node = TreeNode(inorder[index])
node.left = self.buildTree(preorder, inorder[:index])
node.right = self.buildTree(preorder, inorder[index + 1:])
return node
Leave a comment