刷leetcode的时候遇到了如题所示的bug:106从中序与后序遍历序列构造二叉树
意思是TreeNode* 类型不是nullptr_t类型,不能作为表达式的返回值。
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size();
function<TreeNode*(int,int,int,int)> dfs =
[&](int inl,int inr,int pol,int por)
{
if(inl > inr) return nullptr;
TreeNode* cur = new TreeNode(postorder[por]);
int idx = inl;
while(inorder[idx] != postorder[por]){
idx++;
}
int tmp = idx - inl;
cur->left = dfs(inl,inl+tmp-1,pol,pol+tmp-1);
cur->right = dfs(inl+tmp+1,inr,pol+tmp,por-1);
return cur;
};
return dfs(0,n-1,0,n-1);
}
};
由于在lambda表达式中没有显示的确定返回值,编译器看到 第一个 “ return nullptr ”会自动推断其为“ nullptr_t ”类型,这并不符合我们的预期。
要解决这个问题很简单,只需要显示的定义lambda表达式返回类型即可。
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size();
function<TreeNode*(int,int,int,int)> dfs =
[&](int inl,int inr,int pol,int por) -> TreeNode*
{
///实现部分
};
return dfs(0,n-1,0,n-1);
}
};
同时这里的函数需要递归调用,因此必须显示的定义返回类型为 function ,如果使用 auto 自动判断的话,编译器会在推导 dfs 类型的时候遇到内部递归调用的 dfs ,陷入困境。