Last active
August 21, 2017 09:39
-
-
Save jfdm/78990934d29fcc331ed5c9f84e7f5e41 to your computer and use it in GitHub Desktop.
Playing around with Tree's in Swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| protocol Show { | |
| func show() -> String | |
| } | |
| class Tree<T> : Show { | |
| func show() -> String { return "" } | |
| } | |
| class Leaf<T> : Tree<T> { | |
| override func show() -> String { | |
| return "()" | |
| } | |
| } | |
| class Node<T> : Tree<T> { | |
| var left_: Tree<T> | |
| var right_: Tree<T> | |
| var value: T | |
| init(v: T, l: Tree<T>, r: Tree<T>){ | |
| left_ = l | |
| right_ = r | |
| value = v | |
| } | |
| override func show() -> String { | |
| return "{\(self.value) \(self.left_.show()) \(self.right_.show())}" | |
| } | |
| } | |
| var one = Node<Int>(v:1, l:Leaf<Int>(), r:Leaf<Int>()) | |
| var two = Node<Int>(v:2, l:Leaf<Int>(), r:Leaf<Int>()) | |
| var root = Node<Int>(v:3, l:one, r:two) | |
| func printTree<T>(_ t:Tree<T>) -> String { | |
| if let node = t as? Node<T> { | |
| var res = "{" | |
| res += String(describing:node.value) | |
| res += " " | |
| res += printTree(node.left_) | |
| res += " " | |
| res += printTree(node.right_) | |
| res += "}" | |
| return res | |
| // return "{" + node.value + " " + printTree(node.left_) + " " + printTree(node.right_) + "}" | |
| } | |
| return "()" | |
| } | |
| print(printTree(root)) | |
| print(root.show()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment