From 1c10208da8fc9ed7b02c688e131961fa40f03f03 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Tue, 28 May 2024 12:56:29 +0100 Subject: [PATCH] feat: add swift implementation to lcof problem: No.54 (#2940) --- .../面试题54. 二叉搜索树的第k大节点/README.md | 38 +++++++++++++++++++ .../Solution.swift | 33 ++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 lcof/面试题54. 二叉搜索树的第k大节点/Solution.swift diff --git a/lcof/面试题54. 二叉搜索树的第k大节点/README.md b/lcof/面试题54. 二叉搜索树的第k大节点/README.md index 7320ed92a4..8d575de4ac 100644 --- a/lcof/面试题54. 二叉搜索树的第k大节点/README.md +++ b/lcof/面试题54. 二叉搜索树的第k大节点/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/面试题54. 二叉搜索树的第k大节点/Solution.swift b/lcof/面试题54. 二叉搜索树的第k大节点/Solution.swift new file mode 100644 index 0000000000..e77009bfa0 --- /dev/null +++ b/lcof/面试题54. 二叉搜索树的第k大节点/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