Find the target key K in the given binary search tree, return the node that contains the key if K is found, otherwise return null.
Assumptions
- There are no duplicate keys in the binary search tree
public TreeNode search(TreeNode root, int key) {
while (root != null) {
if (root.key == key) {
return root;
} else if (root.key < key) {
root = root.right;
} else {
root = root.left;
}
}
return null;
}