while-loop - 为什么不能等同于指向 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;
}
};
解决方案
没有定义为奇怪的东西(如 7),对于任何给定的指针,和nullptr
之间应该没有区别。x != nullptr
! x
x
可能值得打印出来nullptr
并root
在循环内部以及比较结果(和指针,以防你的树损坏),看看是否发生了奇怪的事情,例如:
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)我最喜欢的口头禅之一是“如有疑问,请打印出来”,就在那里:
- 先让它工作,然后让它快速工作。
- 你不能得到比“错误”更少的优化。
:-)
推荐阅读
- php - 黑白可数对象和不可数对象有什么区别
- java - 如何在 websphere 9 中添加 jsf com.sun.faces
- javascript - 打字稿和javascript中的新行符号和空格
- javascript - 如何逐行获取一个表值,然后使用 jquery 在另一个表中显示这些值
- php - composer - 如何在其他软件包之前先安装/优先安装特定软件包?
- javascript - 将一个对象推入另一个对象
- javascript - 如何在 Javascript 中解析 CSV
- python-3.x - Python - 用字符串替换列表元素
- hyperledger-fabric - 是否需要将 Hyperledger Composer 区块链业务网络部署到 Hyperledger Fabric(多个组织)
- ruby-on-rails - Rails:使用 form_with 的语言环境?