Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import UIKit
- class Node{
- var value: Int
- var left: Node?
- var right: Node?
- init(value: Int){
- self.value = value
- }
- }
- class BST {
- var root: Node?
- init(){}
- func add(_ value:Int){
- add(value, current: root)
- }
- func add(_ value: Int, current: Node?){
- if current == nil {
- var newNode = Node(value:value)
- root = newNode
- return
- }
- var currentNode = current!
- if value < currentNode.value{
- if currentNode.left == nil{
- var newNode = Node(value:value)
- currentNode.left = newNode
- return
- }
- add(value, current: currentNode.left)
- }
- if value >= currentNode.value{
- if currentNode.right == nil{
- var newNode = Node(value: value)
- currentNode.right = newNode
- return
- }
- add(value, current: currentNode.right)
- }
- }
- func contain(_ value: Int) -> Bool{
- return contain(value, current: root)
- }
- func contain (_ value: Int, current: Node?) -> Bool {
- if current == nil {
- return false
- }
- if value == current!.value {
- return true
- }
- if value < current!.value {
- return contain (value, current: current!.left)
- }
- else{
- return contain(value, current: current!.right)
- }
- }
- func printTree(){
- printTree(current: root)
- }
- func printTree(current: Node?){
- if current==nil{
- return
- }
- if current!.left != nil{
- printTree(current:current!.left)
- }
- print(current!.value)
- if current!.right != nil{
- printTree(current:current!.right)
- }
- }
- }
- var myBST = BST()
- myBST.add(3)
- myBST.add(7)
- myBST.add(10)
- myBST.add(-1)
- myBST.printTree()
- print(myBST.contain(7))
- var str = "Hello, playground"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement