From 11187c2700cae65629e0233c7b18496f68ff5ea1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 8 Dec 2023 22:19:37 +0100 Subject: [PATCH] =?UTF-8?q?problems(swift):=20add=20=E2=80=9C606.=20Constr?= =?UTF-8?q?uct=20String=20from=20Binary=20Tree=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../construct-string-from-binary-tree.swift | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 problems/swift/construct-string-from-binary-tree.swift diff --git a/problems/swift/construct-string-from-binary-tree.swift b/problems/swift/construct-string-from-binary-tree.swift new file mode 100644 index 0000000..d5c459b --- /dev/null +++ b/problems/swift/construct-string-from-binary-tree.swift @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + func tree2str(_ root: TreeNode?) -> String { + if let root = root { + let left = tree2str(root.left) + let right = tree2str(root.right) + + var l = "" + if left != "" || right != "" { + l = "(\(left))" + } + + var r = "" + if right != "" { + r = "(\(right))" + } + + return "\(root.val)\(l)\(r)" + } + + return "" + } +}