【发布时间】:2022-01-24 05:28:30
【问题描述】:
有什么区别
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
和
return(checkBst(root->left, minvalue, root));
return(checkBst(root->right, root, maxvalue));
我的整个程序是这样的
bool checkBst(node *root, node * minvalue, node * maxvalue){
if(root == NULL){
return true;
}
if((minvalue && root->data <= minvalue->data) || (maxvalue && root->data >= maxvalue->data)){
return false;
}
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
// return(checkBst(root->left, minvalue, root));
// return(checkBst(root->right, root, maxvalue));
}
【问题讨论】:
-
主要是优化,如果 checkBst(root->left) 已经评估为 false,第一个解决方案将不会调用 checkBst(root->right)。编译器可以这样做,因为无论如何表达式都会计算为假。 (OR 类似,如果左侧已经为真,则不计算右侧)
标签: c++ recursion binary-search-tree