https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
基于上一题进行了挺久的优化,提高到65%,但是还是离100%差挺远。

func buildTree(_ preorder: [Int], _ postorder: [Int]) -> TreeNode? {
    guard !preorder.isEmpty else { return nil }
    guard preorder.count > 1 else { return TreeNode(preorder[0]) }
    let root = TreeNode(postorder.last!)
    if preorder.first! == root.val {
        root.right = buildTree(Array(preorder.dropFirst()), Array(postorder.dropLast()))
    } else if preorder.last! == root.val {
        root.left = buildTree(Array(preorder.dropLast()), Array(postorder.dropLast()))
    } else {
        let list = preorder.split(separator: root.val)
        root.left = buildTree(Array(list[0]), Array(postorder[0..<list[0].count]))
        root.right = buildTree(Array(list[1]), Array(postorder[list[0].count..<postorder.count-1]))
    }
    return root
}

466886BC-395B-4B6C-A841-4D8BBE439BD0