Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add swift implementation to lcof problem: No.54 #2940

Merged
merged 1 commit into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Swift implementation for LCOF 54
  • Loading branch information
klever34 committed May 28, 2024
commit c7635b949124397799904e3cdd0ebd7a214f9631
38 changes: 38 additions & 0 deletions lcof/面试题54. 二叉搜索树的第k大节点/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
33 changes: 33 additions & 0 deletions lcof/面试题54. 二叉搜索树的第k大节点/Solution.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading