File tree 2 files changed +71
-0
lines changed
2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -331,6 +331,44 @@ public class Solution {
331
331
}
332
332
```
333
333
334
+ #### Swift
335
+
336
+ ``` swift
337
+ /* public class TreeNode {
338
+ * public var val: Int
339
+ * public var left: TreeNode?
340
+ * public var right: TreeNode?
341
+ * public init(_ val: Int) {
342
+ * self.val = val
343
+ * self.left = nil
344
+ * self.right = nil
345
+ * }
346
+ * }
347
+ */
348
+
349
+ class Solution {
350
+ private var k: Int = 0
351
+ private var ans: Int = 0
352
+
353
+ func kthLargest (_ root : TreeNode? , _ k : Int ) -> Int {
354
+ self .k = k
355
+ dfs (root)
356
+ return ans
357
+ }
358
+
359
+ private func dfs (_ root : TreeNode? ) {
360
+ guard let root = root, k > 0 else { return }
361
+ dfs (root.right )
362
+ k -= 1
363
+ if k == 0 {
364
+ ans = root.val
365
+ return
366
+ }
367
+ dfs (root.left )
368
+ }
369
+ }
370
+ ```
371
+
334
372
<!-- tabs: end -->
335
373
336
374
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ /* public class TreeNode {
2
+ * public var val: Int
3
+ * public var left: TreeNode?
4
+ * public var right: TreeNode?
5
+ * public init(_ val: Int) {
6
+ * self.val = val
7
+ * self.left = nil
8
+ * self.right = nil
9
+ * }
10
+ * }
11
+ */
12
+
13
+ class Solution {
14
+ private var k : Int = 0
15
+ private var ans : Int = 0
16
+
17
+ func kthLargest( _ root: TreeNode ? , _ k: Int ) -> Int {
18
+ self . k = k
19
+ dfs ( root)
20
+ return ans
21
+ }
22
+
23
+ private func dfs( _ root: TreeNode ? ) {
24
+ guard let root = root, k > 0 else { return }
25
+ dfs ( root. right)
26
+ k -= 1
27
+ if k == 0 {
28
+ ans = root. val
29
+ return
30
+ }
31
+ dfs ( root. left)
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments