解题思路
除了跟节点在是后续遍历的最后一个元素以外,其他的与上一题完全一致,不用细说
106. 从中序与后序遍历序列构造二叉树
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not postorder:
return None
root_val = postorder[-1]
idx = inorder.index(root_val)
root = TreeNode(root_val)
root.left = self.buildTree(inorder[0:idx], postorder[0:idx])
root.right = self.buildTree(inorder[idx+1:], postorder[idx:-1])
return root