Problem
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Algorithm
Recursion. Just use dfs, find the root in the inorder traversal then divided the trees into left sub-trees, roots and right sub-trees and run in recursion.
Code
# 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:
Li = len(inorder)
Lp = len(postorder)
if Lp != Li:
return []
def dfs(iL, iR, pL, pR):
if iL > iR:
return None
L, R = None, None
for r in range(iL, iR+1):
if inorder[r] == postorder[pR]:
L = dfs(iL, r-1, pL, pL-1+r-iL)
R = dfs(r+1, iR, pR-iR+r, pR-1)
break
return TreeNode(postorder[pR], L, R)
return dfs(0, Lp-1, 0, Li-1)