【发布时间】:2021-03-25 12:29:59
【问题描述】:
我正在学习 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为零(或nullptr)时,if (!temp->left)的计算结果为true。当temp->left不为零时,if (temp->left)的计算结果为true。这与显式的if (temp->left != NULL)相同,尽管使用现代 C++ 的样式将是if (temp->left != nullptr)。
标签: c++ data-structures queue binary-tree binary-search-tree