File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change @@ -225,6 +225,49 @@ var maxValue = function (root, k) {
225225};
226226```
227227
228+ #### Swift
229+
230+ ``` swift
231+ /* class TreeNode {
232+ * var val: Int
233+ * var left: TreeNode?
234+ * var right: TreeNode?
235+ * init(_ val: Int) {
236+ * self.val = val
237+ * self.left = nil
238+ * self.right = nil
239+ * }
240+ * }
241+ */
242+
243+ class Solution {
244+ private var k: Int = 0
245+
246+ func maxValue (_ root : TreeNode? , _ k : Int ) -> Int {
247+ self .k = k
248+ return dfs (root).max () ?? 0
249+ }
250+
251+ private func dfs (_ root : TreeNode? ) -> [Int ] {
252+ var ans = [Int ](repeating : 0 , count : k + 1 )
253+ guard let root = root else {
254+ return ans
255+ }
256+ let l = dfs (root.left )
257+ let r = dfs (root.right )
258+
259+ ans[0 ] = (l.max () ?? 0 ) + (r.max () ?? 0 )
260+
261+ for i in 0 ..< k {
262+ for j in 0 ..< k - i {
263+ ans[i + j + 1 ] = max (ans[i + j + 1 ], root.val + l[i] + r[j])
264+ }
265+ }
266+ return ans
267+ }
268+ }
269+ ```
270+
228271<!-- tabs: end -->
229272
230273<!-- solution: end -->
Original file line number Diff line number Diff line change 1+ /* class TreeNode {
2+ * var val: Int
3+ * var left: TreeNode?
4+ * var right: TreeNode?
5+ * 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+
16+ func maxValue( _ root: TreeNode ? , _ k: Int ) -> Int {
17+ self . k = k
18+ return dfs ( root) . max ( ) ?? 0
19+ }
20+
21+ private func dfs( _ root: TreeNode ? ) -> [ Int ] {
22+ var ans = [ Int] ( repeating: 0 , count: k + 1 )
23+ guard let root = root else {
24+ return ans
25+ }
26+ let l = dfs ( root. left)
27+ let r = dfs ( root. right)
28+
29+ ans [ 0 ] = ( l. max ( ) ?? 0 ) + ( r. max ( ) ?? 0 )
30+
31+ for i in 0 ..< k {
32+ for j in 0 ..< k - i {
33+ ans [ i + j + 1 ] = max ( ans [ i + j + 1 ] , root. val + l[ i] + r[ j] )
34+ }
35+ }
36+ return ans
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments