Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
做这道题需要了解二叉排序树的性质,左子树的所有节点都小于根节点,右子树所有节点都大于根节点,这样的一棵树就成为了二叉排序树,很容易想到用递归,当然 判断的时候有很多地方要注意,最需要注意的地方是,我们假设左子树或者右子树已经是二叉排序树了,那当前根节点如何去判断满足不满足二叉排序树的条件,这时候就要去找到左子树最大的节点与当前根节点比较,再找到右子树最小的节点与根节点比较 如果都满足左小右大于根,才满足。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// 根为空或者只有1个节点
if (root == NULL || (root->left == NULL && root->right == NULL)) return true;
// 只有右子树
if (root->left == NULL && root->right->val <= root->val) return false;
else if (root->left == NULL && root->right->val > root->val) return isValidBST(root->right);
// 只有左子树
if (root->right == NULL && root->left->val >= root->val) return false;
else if (root->right == NULL && root->left->val < root->val) return isValidBST(root->left);
// 判断左右子树都有的情况
TreeNode *left_veryRight = root->left->right, *right_veryLeft = root->right->left;
if (root->val <= root->left->val || root->val >= root->right->val) return false;
// 左子树最右节点是否小于根节点
while (left_veryRight)
{
if (root->val <= left_veryRight->val)
return false;
left_veryRight = left_veryRight->right;
}
// 右子树最左节点是否大于根节点
while (right_veryLeft)
{
if (root->val >= right_veryLeft->val)
return false;
right_veryLeft = right_veryLeft->left;
}
return isValidBST(root->left) && isValidBST(root->right);
}
};