106. Construct Binary Tree From Inorder and Postorder Traversal
[Medium] “Given inorder and postorder 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, inorder: List[int], postorder: List[int]) -> TreeNode:
if (not inorder) or (not postorder):
return None
# root is end of postorder
root_val = postorder.pop()
root_index = inorder.index(root_val)
node = TreeNode(root_val)
node.left = self.buildTree(inorder[0:root_index], postorder[:root_index])
node.right = self.buildTree(inorder[(root_index + 1):], postorder[root_index:])
return node