[Leetcode 700] Search in a Binary Search Tree

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Input: root = [4,2,7,1,3], val = 5
Output: []
struct TreeNode* searchBST(struct TreeNode* root, int val){
//boundary
if(!root)
return NULL;

//main
struct TreeNode* ptr = root;
if(val < ptr->val)
ptr = searchBST(ptr->left, val);
else if(val > ptr->val)
ptr = searchBST(ptr->right, val);
else
return ptr;

return ptr;
}
struct TreeNode* searchBST(struct TreeNode* root, int val){

struct TreeNode* ptr = root;
while(ptr){
if(val < ptr->val)
ptr = ptr->left;
else if(val > ptr->val)
ptr = ptr->right;
else
return ptr;
}

return ptr;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store