Recently I read a news about IBM creating a website for swift: IBM Swift Sandbox. That's very interesting. I went to the site and played for a while. This is a good site for beginners to write some experiment codes in web browser.
There are some examples as initials. I picked up tree.swift
to put my hands on writing and playing swift codes.
The output of this example shows notes added to a tree. I wanted to extend this class so that I can print out notes in the tree.
To do that, I added a var root as property value, and a func to print tree notes. Here are my updated codes:
Here is a command to set up swift syntax in VIM
1 2 /* Generic sorted tree implementation. Shows generic 3 classes and recursive functions in Swift. 4 */ 5 6 class TreeNode<T: Comparable> { 7 8 var val: T? 9 var left: TreeNode? 10 var right: TreeNode? 11 var root : Bool = true 12 13 func printMe() { 14 if (self.root) { 15 print(" root:\(self.val!)") 16 } 17 18 if let leftVal = self.left { 19 print(" \(leftVal.val!)<-\(self.val!)") 20 leftVal.root = false 21 leftVal.printMe() 22 } 23 if let rightVal = self.right { 24 print(" \(self.val!)->\(rightVal.val!)") 25 rightVal.root = false; 26 rightVal.printMe() 27 } 28 } 29 //add item based on its value 30 func addNode(val: T) { 31 32 if (self.val == nil) { 33 self.val = val 34 print("Added Head") 35 return 36 } 37 38 if (val < self.val) { 39 40 if let left = self.left { 41 left.addNode(val) 42 } else { 43 let newLeft = TreeNode() 44 newLeft.val = val 45 self.left = newLeft 46 print("Added Left") 47 } 48 } 49 50 if (val > self.val) { 51 52 if let right = self.right { 53 right.addNode(val) 54 } else { 55 let newRight = TreeNode() 56 newRight.val = val 57 self.right = newRight 58 print("Added Right") 59 } 60 } 61 62 } 63 } 64 65 let numbers: Array<Int> = [8, 3, 5, 2, 7, 9, 13, 16, 10, 22] 66 var root = TreeNode<Int>() 67 68 for n in numbers { 69 print(n) 70 root.addNode(n) 71 } 72 73 print("\nTree Notes") 74 root.root = true 75 root.printMe() 76
Here s the result after click on Run button:
Exercises
The above codes can be extended with following 4 exercises:- Add an enumeration type with three enumerators: "Added Head", "Added Left" and "Added Right".
- Add above enum to
TreeNote
class member as an note's added type, oraddType
. - Update
addNode(T) func
with a return type ofTreeNode
, that is, the returning the added node. - Add a member to
TreeNode
:var parent: TreeNode
. UpdateaddNode() func
to set this member value.
0 comments:
Post a Comment