二叉树 105通过前序和中序确定唯一二叉树
利用前序第一个为根节点和终止条件
前序遍历的顺序
[ 根节点, [左子树的前序遍历结果], [右子树的前序遍历结果] ]
中序遍历的顺序
[ [左子树的中序遍历结果], 根节点, [右子树的中序遍历结果] ]
- 先递归地遍历左子树
- 随后遍历根节点
- 最后递归地遍历右子树
后序遍历的顺序
[ [左子树的中序遍历结果], [右子树的中序遍历结果] ,根节点]
- 先递归地遍历左子树
- 随后递归地遍历右子树
- 最后遍历根节点
# 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, preorder: List[int], inorder: List[int]) -> TreeNode:
##定义一个,还是需要用到递归
def build_new_tree(preorder_left:int,preorder_right:int,inorder_left:int,inorder_right:int):
if preorder_left > preorder_right:
return None
preorder_root = preorder_left
inorder_root = index[preorder[preorder_root]]
root = TreeNode(preorder[preorder_root])
size_left_subtree = inorder_root - inorder_left
#递归
root.left = build_new_tree(preorder_root+1,preorder_root+size_left_subtree ,inorder_left,inorder_root-1)
root.right = build_new_tree(preorder_root+size_left_subtree+1,preorder_right,inorder_root+1,inorder_right)
return root
index= {element: i for i, element in enumerate(inorder)}
n = len(preorder)
return build_new_tree(0,n-1,0,n-1)
|