Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

105. Construct Binary Tree from Preorder and Inorder Traversal #124

Open
jrmullen opened this issue Jun 3, 2024 · 0 comments
Open

105. Construct Binary Tree from Preorder and Inorder Traversal #124

jrmullen opened this issue Jun 3, 2024 · 0 comments

Comments

@jrmullen
Copy link
Owner

jrmullen commented Jun 3, 2024

# 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]) -> Optional[TreeNode]:
        if not preorder or not inorder:
            return None
        
        # Preorder traversal -> NODE, LEFT, RIGHT
        # This means that the first element of the `preorder` array will always be the root node
        root = TreeNode(preorder[0])

        # Find the index of the root value in the `inorder` array
        # Inorder traversal -> LEFT, NODE, RIGHT
        # Everything BEFORE the `nodeIndex` is the inorder left subtree
        # Everything AFTER the `nodeIndex` is the inorder right subtree
        nodeIndex = inorder.index(root.val)
        
        # Preorder - element 0 was the root node. Everything after that up to AND INCLUDING the `nodeIndex` is the left subtree
        # Inorder - Everything from the start of the array up to the `nodeIndex` is the left subtree
        root.left = self.buildTree(preorder[1 : nodeIndex + 1], inorder[:nodeIndex])

        # Preorder - Everything after the `nodeIndex` to the end of the array is the right subtree
        # Inorder - Everything after the `nodeIndex` to the end of the array is the right subtree
        root.right = self.buildTree(preorder[nodeIndex + 1:], inorder[nodeIndex + 1:])

        # Return the tree that was build
        return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant