simple python solution


  • 0
    B
        if not preorder:
            return []
        val = preorder.pop(0)
        root = TreeNode(val)
        if not preorder:
            root.left = None
            root.right = None
            return root
        val_index = inorder.index(val)
        l_in = inorder[:val_index]
        l_pre = preorder[:len(l_in)]
        try:
            r_in = inorder[val_index+1:]
        except Exception:
            r_in = []
        if r_in:
            r_pre = preorder[len(l_in):]
        else:
            r_pre = []
        if l_pre:
            root.left = self.buildTree(l_pre, l_in)
        if r_pre:
            root.right = self.buildTree(r_pre, r_in)
        return root

Log in to reply
 

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