题目要求:
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.
class Solution {
public:
bool isValidBST(TreeNode *root)
{
int min_value = numeric_limits<int>::min();
int max_value = numeric_limits<int>::max();
return DFS(root, min_value, max_value);
}
bool DFS(TreeNode* root, int& min_value, int& max_value)
{
if(root == NULL)
return true;
if(root->val > min_value && root->val < max_value &&//进入左孩子节点的时候 最大值更新为当前节点值,进入判断右孩子节点的时候,最小值更新为当前节点值
DFS(root->left, min_value, root->val) &&
DFS(root->right, root->val, max_value))
return true;
return false;
}
};