题解 | #从中序与后序遍历序列构造二叉树#
从中序与后序遍历序列构造二叉树
http://www.nowcoder.com/practice/ab8dde7f01f3440fbbb7993d2411a46b
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param inorder int整型一维数组 中序遍历序列
# @param postorder int整型一维数组 后序遍历序列
# @return TreeNode类
#
class Solution:
def buildTree(self , inorder: List[int], postorder: List[int]) -> TreeNode:
def myBuildTree(inorder_left:int,inorder_right:int,postorder_left:int,postorder_right:int):
if inorder_left > inorder_right or postorder_left>postorder_right:
return None
postorder_root = postorder_right
inorder_root = index[postorder[postorder_root]]
root = TreeNode(postorder[postorder_root])
size_left_subtree = inorder_root - inorder_left
root.left = myBuildTree(inorder_left,inorder_root-1,postorder_left,postorder_left+size_left_subtree-1)
root.right = myBuildTree(inorder_root+1,inorder_right,postorder_left+size_left_subtree,postorder_root-1)
return root
n = len(inorder)
index = {element:i for i,element in enumerate(inorder)}
return myBuildTree(0,n-1,0,n-1)
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param inorder int整型一维数组 中序遍历序列
# @param postorder int整型一维数组 后序遍历序列
# @return TreeNode类
#
class Solution:
def buildTree(self , inorder: List[int], postorder: List[int]) -> TreeNode:
def myBuildTree(inorder_left:int,inorder_right:int,postorder_left:int,postorder_right:int):
if inorder_left > inorder_right or postorder_left>postorder_right:
return None
postorder_root = postorder_right
inorder_root = index[postorder[postorder_root]]
root = TreeNode(postorder[postorder_root])
size_left_subtree = inorder_root - inorder_left
root.left = myBuildTree(inorder_left,inorder_root-1,postorder_left,postorder_left+size_left_subtree-1)
root.right = myBuildTree(inorder_root+1,inorder_right,postorder_left+size_left_subtree,postorder_root-1)
return root
n = len(inorder)
index = {element:i for i,element in enumerate(inorder)}
return myBuildTree(0,n-1,0,n-1)