检查是否为BST

来源:互联网 发布:遗传算法bp神经网络 编辑:程序博客网 时间:2024/05/16 13:51

题目描述:

请实现一个函数,检查一棵二叉树是否为二叉查找树。

给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。

  • 二叉查找树:所有左边的节点小于等于当前节点,而当前节点必须小于所有右边的节点

1、中序遍历二叉树

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Checker {public:    int last = INT_MIN;    bool checkBST(TreeNode* root) {        if (root == nullptr) return true;        if (!(checkBST(root->left))) return false;        if (root->val <= last) return false;        last = root->val;        if (!checkBST(root->right)) return false;        return true;    }};

2、二叉查找树的定义

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Checker {public:    bool checkBST(TreeNode* root) {        return checkBST(root, INT_MIN, INT_MAX);    }    bool checkBST(TreeNode* root, int min, int max) {        if (root == nullptr) return true;        if (root->val < min || root->val >= max) return false;        if (!checkBST(root->left, min, root->val) || !checkBST(root->right, root->val, max))            return false;        return true;    }};
原创粉丝点击