Build a binary tree (swift) and a binary tree swift
Build a binary tree (swift)
PublicclassALTree <T: Comparable> {
Var key: T?
Var left: ALTree?
Var right: ALTree?
Func addNode (key: T ){
If (self. key = nil ){
Self. key = key
Return
}
If (key <self. key ){
If (self. left! = Nil ){
Left !. AddNode (key)
} Else {
Var leftChild: ALTree = ALTree ()
LeftChild. key = key
Self. left = leftChild
}
}
If (key> self. key ){
If (self. right! = Nil ){
Right !. AddNode (key)
} Else {
Var rightChild: ALTree = ALTree ()
RightChild. key = key
Self. right = rightChild
}
}
}}
LetnumberList: Array <Int> = [8, 2, 10, 9, 11, 1, 7]
Varroot = ALTree <Int> ()
Fornumber in numberList {
Root. addNode (number)
} Println (root)
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.