6/21/2020

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

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

The first number of preorder array is the current root. Then use the root number to find the numbers belong to the left sub-tree. And numbers belong to the right sub-tree. Then recursively re-create the tree.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None
        
        root = TreeNode(preorder[0])
        
        i = 0
        while inorder[i] != preorder[0]:
            i += 1
        
        root.left = self.buildTree(preorder[1:1+i], inorder[:i])
        root.right = self.buildTree(preorder[1+i:], inorder[i+1:])
        
        return root

No comments:

Post a Comment