Skip to content

Instantly share code, notes, and snippets.

@davidseek
Created June 16, 2020 22:31
Show Gist options
  • Save davidseek/27d7fb819ad1a405c75a90b922feed29 to your computer and use it in GitHub Desktop.
Save davidseek/27d7fb819ad1a405c75a90b922feed29 to your computer and use it in GitHub Desktop.
func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
/**
Without a root, nothing to find.
This is the exist condition of our recursion.
*/
guard let node = root else {
return nil
}
/**
First we need to check if the
node.val is the target value.
*/
if node.val == val {
return node
/**
Next we need to check if the target value is larger
or smaller than node's.val...
*/
} else if node.val > val {
// ... and continue down the recursion ...
return searchBST(node.left, val)
} else {
// ... and pass the proper sub tree.
return searchBST(node.right, val)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment