【问题标题】:why can't equate pointer to nullptr为什么不能等同于指向 nullptr 的指针
【发布时间】:2021-08-21 04:31:37
【问题描述】:

在以下程序中,我正在搜索 BST 中的最低命令祖先。

这里的主要问题是 !root 不像 root!=nullptr 那样工作。 这里第 1 行完美。但是第 2 行给出了错误的答案。 请说明为什么第 2 行不起作用而第 1 行起作用。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        int small=min(p->val, q->val);
        int big=max(p->val, q->val);
        while(root!=nullptr){   // line 1
        // while(!root){        // line 2
            int x=(root->val);
            if(x>big){
                root=root->left;
            }
            else if(x<small){
                root=root->right;
            }
            else{
                return root;
            }
        }
        return nullptr;
    }
};

【问题讨论】:

  • 顺便说一句,我知道它在评论区而不是代码中,但您确实应该在 C++ 代码中使用 nullptr 而不是 NULL

标签: while-loop null nullptr


【解决方案1】:

没有将nullptr 定义为奇怪的东西(比如7),对于任何给定的指针xx != nullptr! x 之间应该没有区别。

可能值得在循环内部打印出nullptrroot 以及比较结果(和指针,以防你的树损坏),看看是否发生了奇怪的事情,例如:

while (!root) {
    std::cout
        << static_cast<void*>(root) << ' '
        << static_cast<void*>(root->left) << ' '
        << static_cast<void*>(root->right) << ' '
        << static_cast<void*>(nullptr) << ' '
        << (! root) << ' '
        << (root != nullptr) << std::endl;
    int x=(root->val);
    // ... and so on

这样的输出可能有助于显示您的情况出了什么问题(a)


(a) 我最喜欢的口头禅之一是“如有疑问,请打印出来”,就在上面:

  • 先让它工作,然后让它快速工作。
  • 没有比“错误”更糟糕的优化了。

:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多