Skip to content

Commit

Permalink
Create buildTree.py
Browse files Browse the repository at this point in the history
  • Loading branch information
huangsam authored Nov 18, 2024
1 parent b868931 commit 62c4c63
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions python/buildTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

from collections import deque
from typing import Deque, List, Optional

from container.binary_tree import TreeNode


class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
return self.build(deque(preorder), inorder)

def build(self, prequeue: Deque[int], inorder: List[int]) -> Optional[TreeNode]:
if len(inorder) == 0:
return None

idx = inorder.index(prequeue.popleft())
root = TreeNode(inorder[idx])

root.left = self.build(prequeue, inorder[:idx])
root.right = self.build(prequeue, inorder[idx + 1 :])

return root

0 comments on commit 62c4c63

Please sign in to comment.