一.題目
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.
二.解題技巧
三.實現代碼
#include <iostream>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
bool isValidBST(TreeNode* root, int &MinValue, int &MaxValue)
{
if (!root)
{
return true;
}
if (root->left)
{
if (root->val <= root->left->val)
{
return false;
}
int LeftMinValue = 0;
int LeftMaxValue = 0;
if (!isValidBST(root->left, LeftMinValue, LeftMaxValue))
{
return false;
}
else
{
MinValue = LeftMinValue;
if (LeftMaxValue != LeftMinValue)
{
if (root->val <= LeftMaxValue)
{
return false;
}
}
}
}
else
{
MinValue = root->val;
}
if (root->right)
{
if (root->val >= root->right->val)
{
return false;
}
int RightMinValue = 0;
int RightMaxValue = 0;
if (!isValidBST(root->right, RightMinValue, RightMaxValue))
{
return false;
}
else
{
MaxValue = RightMaxValue;
if (RightMaxValue != RightMinValue)
{
if (root->val >= RightMinValue)
{
return false;
}
}
}
}
else
{
MaxValue = root->val;
}
return true;
}
public:
bool isValidBST(TreeNode* root)
{
int MinValue = 0;
int MaxValue = 0;
bool IsLeaf = true;
return isValidBST(root, MinValue, MaxValue);
}
};