π One-stop destination for all your technical interview Preparation π
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the nodeβs value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
class Solution{
public:
TreeNode *searchBST(TreeNode *root, int val){
if (root == NULL) return NULL;
if (root->val == val) return root;
if (val < root->val)
return searchBST(root->left, val);
else
return searchBST(root->right, val);
}
};
class Solution{
public:
TreeNode *searchBST(TreeNode *root, int val){
if (root == NULL) return NULL;
while (root != NULL){
if (root->val == val) return root;
else if (val < root->val) root = root->left;
else root = root->right;
}
return root;
}
};