From c29963f8810da02604e6491da1b8450498c65af0 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Wed, 5 Feb 2025 10:11:32 +0100 Subject: [PATCH] feat: add swift implementation to lcp problem: No.67 (#4026) --- .../README.md" | 40 +++++++++++++++++++ .../Solution.swift" | 36 +++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 "lcp/LCP 67. \350\243\205\351\245\260\346\240\221/Solution.swift" diff --git "a/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" index e4d4babb6c862..b2444818fc494 100644 --- "a/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" +++ "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" @@ -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 + } +} + +``` + diff --git "a/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/Solution.swift" "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/Solution.swift" new file mode 100644 index 0000000000000..56a1d82045ec9 --- /dev/null +++ "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/Solution.swift" @@ -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 + } +}