【问题标题】:Is !temp->left and temp->left!=NULL different?!temp->left 和 temp->left!=NULL 不同吗?
【发布时间】: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-&gt;left != NULL 等价于temp-&gt;left(没有否定)。
  • 是的,这两件事是不同的……事实上相反。当temp-&gt;left(或nullptr)时,if (!temp-&gt;left) 的计算结果为true。当temp-&gt;left 不为零时,if (temp-&gt;left) 的计算结果为true。这与显式的 if (temp-&gt;left != NULL) 相同,尽管使用现代 C++ 的样式将是 if (temp-&gt;left != nullptr)

标签: c++ data-structures queue binary-tree binary-search-tree


【解决方案1】:

temp-&gt;left!=NULL 应替换为 temp-&gt;left 而不是 !temp-&gt;left。以下应该可以解决问题:

if(temp->left && temp->left->val==B || temp->right && temp->right->val==B)

【讨论】:

    【解决方案2】:

    非空指针转换为true,空指针转换为false

    所以temp-&gt;left 转换为布尔值与temp-&gt;left != NULL 相同。
    如果你否定你会发现!temp-&gt;lefttemp-&gt;left == NULL是一样的。

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

    【讨论】:

      【解决方案3】:

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

      !temp->left 如果 temp->left 为 NULL,则为 true

      【讨论】:

      • 这是有道理的!现在我懂了!非常感谢。
      猜你喜欢
      • 2022-11-28
      • 2015-12-11
      • 2011-05-19
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多