首页 > 解决方案 > 为什么不能等同于指向 nullptr 的指针

问题描述

在以下程序中,我正在搜索 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;
    }
};

标签: while-loopnullnullptr

解决方案


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

可能值得打印出来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)我最喜欢的口头禅之一是“如有疑问,请打印出来”,就在那里:

  • 先让它工作,然后让它快速工作。
  • 你不能得到比“错误”更少的优化。

:-)


推荐阅读