iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 55

[Day 54 - 2] Construct Binary Tree from Preorder and Inorder Traversal (Medium)

  • 分享至 

  • xImage
  •  

105. Construct Binary Tree from Preorder and Inorder Traversal

Solution 1: Recursive

class Solution:
    def dfs(self, listPreOrd, listInOrd, idxPreStart, idxPreEnd, idxInStart, idxInEnd):
        if idxPreStart > idxPreEnd or idxInStart > idxInEnd:
            return None
        
        # Linear search to locate the root node
        rootOfBinaryTree = TreeNode(listPreOrd[idxPreStart])
        idxOfRoot = listInOrd.index(listPreOrd[idxPreStart], idxInStart, idxInEnd + 1)
        
        # Split left subtree
        lenOfLftTree = idxOfRoot - idxInStart
        lftSubTree = self.dfs(listPreOrd, listInOrd, 
                              idxPreStart + 1, idxPreStart + lenOfLftTree, 
                              idxInStart, idxInStart + lenOfLftTree - 1)
        # Split right subtree
        lenOfRhtTree = idxInEnd - idxOfRoot
        RhtSubTree = self.dfs(listPreOrd, listInOrd, 
                              idxPreStart + lenOfLftTree + 1, idxPreEnd, 
                              idxOfRoot + 1, idxInEnd)
        
        # Combine and return the rebuild result
        rootOfBinaryTree.left = lftSubTree
        rootOfBinaryTree.right = RhtSubTree
        return rootOfBinaryTree
    
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        idxPreStart, idxPreEnd = 0, len(preorder) - 1
        idxInStart, idxInEnd = 0, len(inorder) - 1
        rootOfBinaryTree = self.dfs(preorder, inorder, idxPreStart, idxPreEnd, idxInStart, idxInEnd)
        return rootOfBinaryTree

Time Complexity: O(N)
Space Complexity: O(N) // Recursive call stack

Solution 2: Recursive + Hash (Optimized)

Time Complexity: O(N)
Space Complexity: O(N)

Reference

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution


上一篇
[Day 54 - 1] Binary Tree Maximum Path Sum (Hard)
下一篇
[Day 55] Find First and Last Position of Element in Sorted Array (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言