Last active
March 22, 2018 17:37
-
-
Save Abhishek9634/687dd37c7a7202cb84c4479771797957 to your computer and use it in GitHub Desktop.
This file contains 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
class BinaryTree<T: Comparable & CustomStringConvertible> { | |
private var rootNode: TreeNode<T>? | |
func insert(element: T) { | |
let node = TreeNode(data: element) | |
if let rootNode = self.rootNode { | |
self.insert(rootNode, node) | |
} else { | |
self.rootNode = node | |
} | |
} | |
// RECURSIVE FUNCTION | |
private func insert(_ rootNode: TreeNode<T>, _ node: TreeNode<T>) { | |
if rootNode.data > node.data { | |
if let leftNode = rootNode.leftNode { | |
self.insert(leftNode, node) | |
} else { | |
rootNode.leftNode = node | |
} | |
} else { | |
if let rightNode = rootNode.rightNode { | |
self.insert(rightNode, node) | |
} else { | |
rootNode.rightNode = node | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment