[LeetCode][Python3] 105. Construct Binary Tree from Preorder and Inorder Traversal

티스토리 메뉴 펼치기 댓글수0

프로그래밍/LeetCode

[LeetCode][Python3] 105. Construct Binary Tree from Preorder and Inorder Traversal

snoopybox
댓글수0

Problem :

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


My Solution :

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def build(preorder, inorder, left, right):
if left < right:
root = TreeNode(preorder[self.pre_idx])
root_idx = inorder.index(root.val, left, right)
self.pre_idx += 1
root.left = build(preorder, inorder, left, root_idx)
root.right = build(preorder, inorder, root_idx+1, right)
return root

self.pre_idx = 0
return build(preorder, inorder, 0, len(inorder))
맨위로

https://www.snoopybox.co.kr/1969

신고하기