105. Construct Binary Tree from Preorder and Inorder Traversal
[Medium] “Given preorder and inorder traversal of a tree, construct the binary tree.."
Python3:
# 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) or (not inorder):
return None
# root is start of preorder
root_val = preorder.pop(0)
root_index = inorder.index(root_val)
node = TreeNode(root_val)
node.left = self.buildTree(preorder[:root_index], inorder[0:root_index])
node.right = self.buildTree(preorder[root_index:], inorder[(root_index + 1):])
return node