-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindInBST.cpp
More file actions
31 lines (27 loc) · 932 Bytes
/
FindInBST.cpp
File metadata and controls
31 lines (27 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// https://leetcode.com/problems/search-in-a-binary-search-tree/
// O(n) time in worst case scenario and O(1) in space as no new vars were created
TreeNode* searchBST(TreeNode* root, int val) {
// if(root == NULL)
// return NULL;
// else if(root->val == val)
// return root;
// else if (root->val >= val)
// return searchBST(root->left, val);
// else if (root->val <= val)
// return searchBST(root->right, val);
// return NULL;
// while(root != NULL)
// {
// if(root->val == val)
// return root;
// else if (root->val >= val)
// root = root->left;
// else if (root->val <= val)
// root = root->right;
// }
// return NULL;
while (root != NULL && root->val != val) {
root = (root->val > val) ? root->left : root->right;
}
return root;
}