判断一棵树是不是二叉搜索树

(一)递归判断

递归判断时,在结点值为整型时,必须指定初始最小值为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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值