Skip to main content

106. Construct Binary Tree from Inorder and Postorder Traversal

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal

Python

Study only try

Not self solution, the answer from here

class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not inorder or not postorder:
return None
root = postorder[-1]
index = inorder.index(root)
ret = TreeNode(postorder.pop())
ret.right = self.buildTree(inorder[index+1:], postorder)
ret.left = self.buildTree(inorder[:index], postorder)
return ret

Second try

Solution which more Pythonic

class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not inorder or not postorder:
return None

root_val = postorder[-1]
root_index = inorder.index(root_val)

return TreeNode(
val=root_val,
left=self.buildTree(
inorder[:root_index],
postorder[:root_index]
),
right=self.buildTree(
inorder[root_index+1:],
postorder[root_index:-1]
)
)