问题描述
我正在学习 C++ 中的二叉树,在我的实践中我有很多时间被替换
temp->left!=NULL 与 !temp->left
例如这里是在 C++ 中查找二叉树中的表亲的代码
vector<int> Solution::solve(TreeNode* A,int B) {
queue<pair<TreeNode *,int>> q;
q.push({A,0});
vector<int> ans;
int reqdepth=-1;
int depth;
while(!q.empty()){
TreeNode *temp=q.front().first;
depth=q.front().second;
if(depth==reqdepth) break;
q.pop();
/* LOOK HERE */ if(temp->left!=NULL && temp->left->val==B || temp->right!=NULL && temp->right->val==B){ /*LOOK HERE */
reqdepth=depth+1;
continue;
}
else {
if(temp->left) q.push({temp->left,depth+1});
if(temp->right) q.push({temp->right,depth+1});
}
}
while(!q.empty()){
ans.push_back(q.front().first->val);
q.pop();
}
return ans;
}
在这段代码中,如果更改了粗体行,即使它符合要求也没有给出正确的解决方案。 请让我知道这些符号是否不同,如果不同,那么如何?
解决方法
temp->left!=NULL
应替换为 temp->left
而不是 !temp->left
。以下应该可以解决问题:
if(temp->left && temp->left->val==B || temp->right && temp->right->val==B)
,
非空指针转换为 true
,空指针转换为 false
。
所以 temp->left
转换为布尔值与 temp->left != NULL
相同。
如果您否定您发现 !temp->left
与 temp->left == NULL
相同。
换句话说,事实与你所相信的相反。
,temp->left!=NULL 如果 temp->left 不是 NULL 则为真
!temp->left 如果 temp->left 为 NULL 则为真