Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

105. Construct Binary Tree from Preorder and Inorder Traversal

Recursive Approach

  • use hashmap, track value index relationship
  • use queue (preorder) to get the next root
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        n = len(preorder)
        q = deque(preorder)
        hm = {v: i for i, v in enumerate(inorder)}

        def build(start: int, end: int) -> Optional[TreeNode]:
            if start > end:
                return None

            value = q.popleft()
            idx = hm[value]

            return TreeNode(value, build(start, idx - 1), build(idx + 1, end))

        return build(0, n - 1)
time complexityspace complexity
\( O(n) \)\( O(n) \)