- class Solution:
- def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
- if not postorder:
- return None
- root_val=postorder[-1]
- root=TreeNode(root_val)
- if len(postorder)==1:
- return root
- left_in=inorder[:inorder.index(root_val)]
- right_in=inorder[inorder.index(root_val)+1:]
- left_post=postorder[:len(left_in)] #!!!
- right_post=postorder[len(left_in):len(postorder)-1] #!!!
- root.left=self.buildTree(left_in,left_post)
- root.right=self.buildTree(right_in,right_post)
- return root
105. 从前序与中序遍历序列构造二叉树
- class Solution:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
- if not preorder:
- return None
- root_val=preorder[0]
- root=TreeNode(root_val)
- inorder_left=inorder[:inorder.index(root_val)]
- inorder_right=inorder[inorder.index(root_val)+1:]
- preorder_left=preorder[1:1+len(inorder_left)]
- preorder_right=preorder[1+len(inorder_left):]
- root.left=self.buildTree(preorder_left,inorder_left)
- root.right=self.buildTree(preorder_right,inorder_right)
- return root
注意11,12行区间选择