Python solution


  • 0
    A

    Build the tree recursively

    class Solution(object):
        def buildTreeT(self, inorder, postorder, s1, e1, s2, e2):
            if e2-s2 <= 0:
                return None
        
            node = TreeNode(postorder[e2-1])
            i = s1
            while i < e1:
                if inorder[i] == node.val:
                    break
                i += 1
    
            node.left = self.buildTreeT(inorder, postorder, s1, i, s2, (s2+(i-s1)))
            node.right = self.buildTreeT(inorder, postorder, i+1, e1, (s2+(i-s1)), e2-1)
            return node
    
        def buildTree(self, inorder, postorder):
            return self.buildTreeT(inorder, postorder, 0, len(inorder), 0, len(postorder))

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.