My code is
TreeNode *sortedArrayToBST(vector<int> &num) {
function<TreeNode*(int,int)> func=
[&func,&num](int s, int e){
TreeNode* p = NULL;
if(s>e) return NULL; // change to return p would compile
int m = (s+e)/2;
p = new TreeNode(num[m]);
p->left = func(s,m-1);
p->right = func(m+1,e);
return p;
};
return func(0,num.size()-1);
}
Solutions.cpp:957:21: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
Solutions.cpp:959:29: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:959:29: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]
Solutions.cpp:962:12: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:962:12: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]
I fixed the code by creating a NULL of the type TreeNode*. My question is how to create a NULL with a type, so that I don't need to declare a temporary variable just to return NULL pointer. Something like NULL(TreeNode);
Use:
function<TreeNode*(int,int)> func=
[&func,&num](int s, int e) -> TreeNode* /*explicitly define return type*/ {
//nullptr is beter than NULL with C++11
TreeNode* p = nullptr;
if(s>e) return nullptr; // we return nullptr here
int m = (s+e)/2;
p = new TreeNode(num[m]);
p->left = func(s,m-1);
p->right = func(m+1,e);
return p;
};
See http://www.stroustrup.com/C++11FAQ.html#nullptr (for some info on nullptr)
Why you get compiler errors
NULL is actually an integer and this causes some confusion when the compiler tries to determine the return type of your lambda (you return an integer when you write return NULL and later down the line you also have a return p (which is a TreeNode*). So the compiler does not know what type should it deduce for the return type of the lambda (is it an int or a pointer to TreeNode)?
You can disambiguate explicitly state the return type and use nullptr (just because this is how you should do it in C++11).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With