Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.14 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5. class Node{
  6.     var value: Int
  7.     var left: Node?
  8.     var right: Node?
  9.    
  10.     init(value: Int){
  11.         self.value = value
  12.     }
  13. }
  14.  
  15. class BST {
  16.     var root: Node?
  17.     init(){}
  18.  
  19.     func add(_ value:Int){
  20.         add(value, current: root)
  21.     }
  22.     func add(_ value: Int, current: Node?){
  23.         if current == nil {
  24.             var newNode = Node(value:value)
  25.             root = newNode
  26.             return
  27.         }
  28.         var currentNode = current!
  29.         if value < currentNode.value{
  30.             if currentNode.left == nil{
  31.                 var newNode = Node(value:value)
  32.                 currentNode.left = newNode
  33.                 return
  34.             }
  35.             add(value, current: currentNode.left)
  36.         }
  37.         if value >= currentNode.value{
  38.             if currentNode.right == nil{
  39.                 var newNode = Node(value: value)
  40.                 currentNode.right = newNode
  41.                 return
  42.             }
  43.             add(value, current: currentNode.right)
  44.         }
  45.     }
  46.    
  47.     func contain(_ value: Int) -> Bool{
  48.         return contain(value, current: root)
  49.     }
  50.    
  51.     func contain (_ value: Int, current: Node?) -> Bool {
  52.         if current == nil {
  53.             return false
  54.         }
  55.         if value == current!.value {
  56.             return true
  57.         }
  58.         if value < current!.value {
  59.             return contain (value, current: current!.left)
  60.         }
  61.         else{
  62.             return contain(value, current: current!.right)
  63.         }
  64.        
  65.     }
  66.    
  67.     func printTree(){
  68.         printTree(current: root)
  69.     }
  70.     func printTree(current: Node?){
  71.         if current==nil{
  72.             return
  73.         }
  74.         if current!.left != nil{
  75.             printTree(current:current!.left)
  76.         }
  77.         print(current!.value)
  78.         if current!.right != nil{
  79.             printTree(current:current!.right)
  80.         }
  81.     }
  82.    
  83.    
  84. }
  85.  
  86.  
  87. var myBST = BST()
  88. myBST.add(3)
  89. myBST.add(7)
  90. myBST.add(10)
  91. myBST.add(-1)
  92. myBST.printTree()
  93. print(myBST.contain(7))
  94.  
  95.  
  96.  
  97. var str = "Hello, playground"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement