1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? { let dict = inorder.enumerated().reduce(into: [Int:Int
func helper(_ inRange: (Int, Int), _ postI: Int) -> TreeNode? { if postI < 0 { return nil } let v = postorder[postI] if let i = dict[v], i >= inRange.0 && i <= inRange.1 { let n = TreeNode(v) n.left = helper((inRange.0, i-1), postI-1) n.right = helper((i+1, inRange.1), postI-1) return n } else { return helper(inRange, postI-1) } }
return helper((0, inorder.count-1), postorder.count-1) } }
|