(一)递归判断
递归判断时,在结点值为整型时,必须指定初始最小值为INT_MIN,最大值为INT_MAX,每次递归时,传入上一层的结点值最为判断依据。
bool JudgeBst_Recur(TreeNode *node, int min, int max){
if(node == NULL) return true;
if(node->val < min || node->val > max) return false;
return JudgeBst_Recur(node->left, min, node->val) && JudgeBst_Recur(node->right, node->val, max);
}
(二)非递归判断
BST的中序遍历,一定是一个非递减序列,后一个结点值大于等于前一个结点值,采用二叉树的中序遍历,并记录下前一个结点,比较前一节点和当前结点的值。
bool JudgeBst(TreeNode *node){
if(node == NULL) return true;
stack<TreeNode*> s;
s.push(node);
TreeNode *prevnode = NULL, *curnode = NULL;
while(!s.empty()){
while(curnode = s.top()) s.push(curnode->left);
s.pop();
if(!s.empty()){
curnode = s.top();
s.pop();
if(NULL != prevnode){
if(curnode->val < prevnode->val)
return false;
}
prevnode = curnode;
s.push(curnode->right);
}
}
return true;
}
测试接口:
int main(void)
{
TreeNode *root = NULL;
PreoderBuildTree(root);
if(JudgeBst_Recur(root, INT_MIN, INT_MAX))
std::cout << "True" << std::endl;
else
std::cout << "False" << std::endl;
if(JudgeBst(root))
std::cout << "True" << std::endl;
else
std::cout << "False" << std::endl;
}