# 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]) -> Optional[TreeNode]:
if not preorder or not inorder:
return None
root=TreeNode(preorder[0])
root_index=inorder.index(preorder[0])
root.left=self.buildTree(preorder[1:1+root_index],inorder[:root_index])
root.right=self.buildTree(preorder[1+root_index:],inorder[root_index+1:])
return root
leetcode106.从中序与后序遍历序列构造二叉树、leetcode105.从前序与中序遍历序列构造二叉树
2024-01-05 22:12:03 29 阅读