# 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 inorder or not postorder:
return
root = TreeNode(postorder[-1])
index = inorder.index(postorder[-1])
# 要抛出根节点 形参的 inorder 和 postorder 长度要相等
root.left = self.buildTree(inorder[:index], postorder[:index])
# 中序根节点在index处 后序根节点在-1索引处
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root
网友评论