判断是否是一个二叉搜索树

定义一个二叉树

#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
using namespace std;

class Node{
public:
    int value;
    Node* left;
    Node* right;
    Node(int value):value(value){
        left = nullptr;
        right = nullptr;
    }
};

生成一个搜索二叉树

//生成一个二叉搜索树
Node *binarySearchTreeInit(){
    Node *head = new Node(4);
    head->left = new Node(2);
    head->right = new Node(6);
    head->left->left = new Node(1);
    head->left->right = new Node(3);
    head->right->left = new Node(5);
    head->right->right = new Node(7);
    return head;
}

三种算法判断

//判断一个二叉树是否是搜索二叉树
//前中后序遍历(任选一个)递归
static int preValue = INT_MIN;
bool isBSTbyRecur(Node *head){
    if(head == nullptr){
        return true;
    }
    bool isABST = isBSTbyRecur(head->left);
    if(!isABST){
        return false;
    }
    if(preValue >= head->value){
        return false;
    }else{
        preValue = head->value;
    }
    return isBSTbyRecur(head->right);
}

//中序遍历判断是否是搜索树
bool isBSTByNoRecur(Node *head){
    if(head == nullptr){
        return true;
    }
    stack<Node*> s;
    int preValueInNoRecur = INT_MIN;
    while(!s.empty() || head != nullptr){
        if(head != nullptr){
            s.push(head);
            head = head->left;
        }else{
            head = s.top();
            s.pop();
            if(preValueInNoRecur >= head->value){
                return false;
            }else{
                preValueInNoRecur = head->value;
            }
            head = head->right;
        }
    }
    return true;
}
//递归判断(二叉树动态规划方法)
class ReturnData{
public:
    bool isSearch;
    int minValue;
    int maxValue;
    ReturnData(bool is, int min, int max):
    isSearch(is), minValue(min), maxValue(max)
    {}
};
ReturnData* isBSTByDP(Node *head){
    if(head == nullptr){
        return nullptr;
    }
    int minValue = head->value;
    int maxValue = head->value;
    ReturnData *rd1 = isBSTByDP(head->left);
    ReturnData *rd2 = isBSTByDP(head->right);
    if(head->left != nullptr){
        minValue = min(minValue, rd1->minValue);
        maxValue = max(maxValue, rd1->maxValue);
    }
    if(head->right != nullptr){
        minValue = min(minValue, rd2->minValue);
        maxValue = max(maxValue, rd2->maxValue);
    }
#if 1
    bool isSearch = true;
    if(head->left!= nullptr
        &&
        (!rd1->isSearch || rd1->maxValue >= head->value)){
        isSearch = false;
    }
    if(head->right!= nullptr
       &&
       (!rd2->isSearch || rd2->minValue <= head->value)){
        isSearch = false;
    }
#else
    bool isSearch = false;
    if(head->left!= nullptr?(rd1->isSearch && rd1->maxValue<head->value):true
        &&
       head->right!= nullptr?(rd2->isSearch && rd2->minValue>head->value):true){
        isSearch = true;
    }
#endif
    return new ReturnData(isSearch, minValue, maxValue);
}

posted @ 2021-08-03 18:08  蘑菇王国大聪明  阅读(52)  评论(0编辑  收藏  举报