挺奇怪的,感觉递归的方法已经够快了,看部分Java实现beats 100%的,也用的差不多思路,但是swift这个不知道哪里能提速,先放着。

func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
	guard !preorder.isEmpty else { return nil }
	guard preorder.count > 1 else { return TreeNode(preorder[0]) }
	let root = TreeNode(preorder[0])
	let i = inorder.firstIndex(of: preorder[0])!
	root.left = buildTree(Array(preorder[1..<i+1]), Array(inorder[0..<i]))
	root.right = buildTree(Array(preorder[i+1..<preorder.count]), Array(inorder[i+1..<inorder.count]))
	return root
}

C7600382-AE02-4942-8FB3-BB6197C29623