TreeNode* searchBST(TreeNode* root, int val) {
if(root==nullptr)return nullptr;
if(root->val==val)return root;
if(root->val<val)return searchBST(root->right,val);
if(root->val>val)return searchBST(root->left,val);
}
root is a given BST,val is the target value to search.
when i compile this code there is an error says non-void function does not return a value in all control paths
if i add return nullptr;
in the end of the code it will run.
problem is that how the control flow will go to a path without return value.
assume that root={4,2,7,1,3}
if val=2 or val =7, the code will give the right answer
if val=8,the control flow goes like 4->7->nullptr,and it will return nullptr,which is also right.
so i dont understand how why there is no return value in some control path.
i asked GPT and also do some dedcution in paper,including the target value is and is not in the BST.
i think since i add an if(root==nullptr)return nullptr;
in the front of the code, it’s unnecessary to add one in the end.
i really want to know that under what circumstance this recursion will go in to a path with no return value