mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(swift): add “606. Construct String from Binary Tree”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
ffa227587e
commit
11187c2700
1 changed files with 37 additions and 0 deletions
37
problems/swift/construct-string-from-binary-tree.swift
Normal file
37
problems/swift/construct-string-from-binary-tree.swift
Normal file
|
@ -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 ""
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue