Created
May 16, 2019 22:36
-
-
Save Mintri1199/e07b8a8b74876bbda4e60e4bc4643b18 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 DecimalSearchTree{ | |
... | |
func search(number: String) -> Any?{ | |
// Return an item in this decimal search tree matching the given number, | |
// or nil if the given item is not found. | |
if let node = findNodeRecursive(number: number, node: self.root) { | |
return node.data | |
} else { | |
return nil | |
} | |
} | |
func findNodeRecursive(number: String, node: DecimalTreeNode) -> DecimalTreeNode? { | |
/* Return the node containing the given item in this decimal search tree, | |
or None if the given item is not found. Search is performed recursively | |
starting from the given node (give the root node to start recursion). */ | |
if number.count == 0 { | |
// Signalling that the tree has a path that contains all the numbers | |
return node | |
} | |
// Use the first number of the string as index to the child node | |
let nextIndex = Int(number.prefix(1)) | |
// Drop the first number of the string | |
let remainder = String(number.dropFirst()) | |
// Check if there is a child node | |
if let nextNode = node.next[nextIndex!] { | |
// If so then call the function again with the remainder string | |
// and the child node in the parameters | |
return findNodeRecursive(number: remainder, node: nextNode) | |
} else { | |
// Did not find a node and the remainder still contains characters. | |
// Meaning the tree doesn't have a path that contains all the numbers. | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment