Created
June 16, 2020 22:31
-
-
Save davidseek/27d7fb819ad1a405c75a90b922feed29 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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