!temp->left 和 temp->left!=NULL 不同吗?

问题描述

我正在学习 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->lefttemp->left == NULL 相同。

换句话说,事实与你所相信的相反。

,

temp->left!=NULL 如果 temp->left 不是 NULL 则为真

!temp->left 如果 temp->left 为 NULL 则为真