[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: []
  • The number of nodes in the tree is in the range [1, 5000].
  • 1 <= Node.val <= 107
  • root is a binary search tree.
  • 1 <= val <= 107
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;
}

--

--

--

Hi I am Samuel

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Uploading array of images using multipart/form-data in swift.

Connecting our Information and Working with Maps

AuroraFS beta network airdrop tutorial

PentesterAcademy’s Red Teaming Expert review

Collection Framework In Java

Most powerful python modules in 2020

Pumpkin Picking With NJ Party Bus https://t.co/e5qSBerAgG

Using Google Translate in Python Applications

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
Samuel Liu

Samuel Liu

Hi I am Samuel

More from Medium

Binary Tree Inorder Traversal

Sorting Techniques 2.0

Recursive functions

Beginner’s guide to Supercomputers: