Skip to content

Commit

Permalink
feat: add swift implementation to lcp problem: No.67 (#4026)
Browse files Browse the repository at this point in the history
  • Loading branch information
klever34 authored Feb 5, 2025
1 parent b901bf8 commit c29963f
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lcp/LCP 67. 装饰树/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,46 @@ func expandBinaryTree(root *TreeNode) *TreeNode {
}
```

#### Swift

```swift
/* class TreeNode {
* var val: Int
* var left: TreeNode?
* var right: TreeNode?
* init() { self.val = 0; self.left = nil; self.right = nil }
* init(_ val: Int) { self.val = val; self.left = nil; self.right = nil }
* init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/

class Solution {
func expandBinaryTree(_ root: TreeNode?) -> TreeNode? {
return dfs(root)
}

private func dfs(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }

let leftChild = dfs(root.left)
let rightChild = dfs(root.right)

if let leftChild = leftChild {
root.left = TreeNode(-1, leftChild, nil)
}
if let rightChild = rightChild {
root.right = TreeNode(-1, nil, rightChild)
}
return root
}
}

```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
36 changes: 36 additions & 0 deletions lcp/LCP 67. 装饰树/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* class TreeNode {
* var val: Int
* var left: TreeNode?
* var right: TreeNode?

* init() { self.val = 0; self.left = nil; self.right = nil }
* init(_ val: Int) { self.val = val; self.left = nil; self.right = nil }
* init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/

class Solution {
func expandBinaryTree(_ root: TreeNode?) -> TreeNode? {
return dfs(root)
}

private func dfs(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }

let leftChild = dfs(root.left)
let rightChild = dfs(root.right)

if let leftChild = leftChild {
root.left = TreeNode(-1, leftChild, nil)
}
if let rightChild = rightChild {
root.right = TreeNode(-1, nil, rightChild)
}

return root
}
}

0 comments on commit c29963f

Please sign in to comment.