106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
postorder 的順序,就是根節點是最後一個數字
inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
# 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:
table = {}
for idx, val in enumerate(inorder):
table[val] = idx
def traverse(leftIndex, rightIndex):
if leftIndex > rightIndex:
return None
root = TreeNode(postorder.pop())
rootIndex = table[root.val]
root.right = traverse(rootIndex + 1, rightIndex)
root.left = traverse(leftIndex, rootIndex - 1)
return root
return traverse(0, len(inorder) - 1)