Binary tree from order
It's MLK day, here's some more binary tree questions
preorder and inorder: problem
from typing import Optional
# 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:
return None
val = preorder[0]
split_index = -1
for i, v in enumerate(inorder):
if v == val:
split_index = i
left_preorder = preorder[1:1+split_index]
right_preorder = preorder[1+split_index:]
left_inorder = inorder[0:split_index]
right_inorder = inorder[split_index+1:]
return TreeNode(
val = val,
left = self.buildTree(left_preorder, left_inorder),
right = self.buildTree(right_preorder, right_inorder)
)
inorder and postorder: problem
from typing import Optional
# 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, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not inorder:
return None
val = postorder[-1]
split_index = -1
for i, v in enumerate(inorder):
if v == val:
split_index = i
left_inorder = inorder[0:split_index]
right_inorder = inorder[split_index+1:]
left_postorder = postorder[0:split_index]
right_postorder = postorder[split_index:len(postorder)-1]
return TreeNode(
val=val,
left=self.buildTree(left_inorder, left_postorder),
right=self.buildTree(right_inorder, right_postorder)
)