針對一個節點,有下列四種狀況:node
若是當前節點的左右子節點值知足二叉搜索樹的條件,咱們能夠遞歸判斷左右子樹是否爲二叉搜索樹。若是左右子樹也知足二叉搜索樹條件,同時左子樹最大節點(也即前驅結點)值小於當前節點值,右子樹最小節點(也即後繼結點)值大於當前節點值,那麼整棵樹即爲二叉搜索樹。spa
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == NULL || (root->left == NULL && root->right == NULL)) return true;
else if (root->left != NULL && root->right == NULL)
{
if (root->left->val >= root->val) return false;
else return isValidBST(root->left) && isValidprev_node(root->left, root->val);
}
else if (root->left == NULL && root->right != NULL)
{
if (root->right->val <= root->val) return false;
else return isValidBST(root->right) && isValidnext_node(root->right, root->val);
}
else
{
if (root->right->val <= root->val || root->left->val >= root->val) return false;
else return isValidBST(root->left) && isValidprev_node(root->left, root->val)
&& isValidBST(root->right) && isValidnext_node(root->right, root->val);
}
}
// 前驅節點是否有效
bool isValidprev_node(TreeNode* root, int data) {
while (root->right != NULL)
{
root = root->right;
}
if (root->val < data) return true;
else return false;
}
// 後繼節點是否有效
bool isValidnext_node(TreeNode* root, int data) {
while (root->left != NULL)
{
root = root->left;
}
if (root->val > data) return true;
else return false;
}
};
複製代碼
獲取更多精彩,請關注「seniusen」! code