diff --git "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" index d7ae1aa3cb80c..5139b8a574f28 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" @@ -350,6 +350,50 @@ public class Solution { } ``` +#### Swift + +```swift +/* public class TreeNode { +* public var val: Int +* public var left: TreeNode? +* public var right: TreeNode? +* public init(_ val: Int) { +* self.val = val +* self.left = nil +* self.right = nil +* } +* } +*/ + +class Solution { + private var d = [Int: Int]() + private var preorder: [Int] = [] + private var inorder: [Int] = [] + + func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { + let n = inorder.count + for i in 0.. TreeNode? { + if n < 1 { + return nil + } + let k = d[preorder[i]]! + let l = k - j + let root = TreeNode(preorder[i]) + root.left = dfs(i + 1, j, l) + root.right = dfs(i + 1 + l, k + 1, n - l - 1) + return root + } +} +``` + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.swift" "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.swift" new file mode 100644 index 0000000000000..61d06b294616f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/Solution.swift" @@ -0,0 +1,39 @@ +/* public class TreeNode { +* public var val: Int +* public var left: TreeNode? +* public var right: TreeNode? +* public init(_ val: Int) { +* self.val = val +* self.left = nil +* self.right = nil +* } +* } +*/ + +class Solution { + private var d = [Int: Int]() + private var preorder: [Int] = [] + private var inorder: [Int] = [] + + func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { + let n = inorder.count + for i in 0.. TreeNode? { + if n < 1 { + return nil + } + let k = d[preorder[i]]! + let l = k - j + let root = TreeNode(preorder[i]) + root.left = dfs(i + 1, j, l) + root.right = dfs(i + 1 + l, k + 1, n - l - 1) + return root + } +} \ No newline at end of file