106. Construct Binary Tree from Inorder and Postorder Traversal
思路见Q105:
105. Construct Binary Tree from Preorder and Inorder Traversal这题的主要变化是:
需要逆序遍历
postorder
(其实逆序postorder
就是先搜right subtree的preorder
)相应地,要先确定 rght subtree 再去确定 left
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder or not postorder: return None
rootVal = postorder.pop()
root = TreeNode(rootVal)
idx = inorder.index(rootVal)
root.right = self.buildTree(inorder[idx+1:], postorder)
root.left = self.buildTree(inorder[:idx], postorder)
return root
Previous105. Construct Binary Tree from Preorder and Inorder TraversalNext979. Distribute Coins in Binary Tree
Last updated
Was this helpful?