【发布时间】: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