diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" index 7320ed92a469c..8d575de4ac002 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" @@ -331,6 +331,44 @@ 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 k: Int = 0 + private var ans: Int = 0 + + func kthLargest(_ root: TreeNode?, _ k: Int) -> Int { + self.k = k + dfs(root) + return ans + } + + private func dfs(_ root: TreeNode?) { + guard let root = root, k > 0 else { return } + dfs(root.right) + k -= 1 + if k == 0 { + ans = root.val + return + } + dfs(root.left) + } +} +``` + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.swift" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.swift" new file mode 100644 index 0000000000000..e77009bfa0a0e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution.swift" @@ -0,0 +1,33 @@ +/* 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 k: Int = 0 + private var ans: Int = 0 + + func kthLargest(_ root: TreeNode?, _ k: Int) -> Int { + self.k = k + dfs(root) + return ans + } + + private func dfs(_ root: TreeNode?) { + guard let root = root, k > 0 else { return } + dfs(root.right) + k -= 1 + if k == 0 { + ans = root.val + return + } + dfs(root.left) + } +} \ No newline at end of file