题目链接:https://leetcode.com/problems/validate-binary-search-tree/
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.
思路:要判断一个树是否是二叉树,要看是否满足三个条件:
1. 左子树包含的节点值都满足小于根节点
2. 右子树包含的节点值都满足大于根节点
3. 左右子树都是二叉排序树
在本题中只需要递归的遍历左右子树即可,给定一个范围空间,表明当前值的合法区间。需要注意的是初始的区间要超出[INT_MIN, INT_MAX]范围,不然会无法判断边界的值。
代码如下:
/**
* 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 DFS(TreeNode* root, long Min, long Max)
{
if(!root) return true;
if(root->val <= Min || root->val >= Max) return false;
auto left = root->left, right = root->right;
return DFS(left, Min, root->val) && DFS(right, root->val, Max);
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
return DFS(root, LONG_MIN, LONG_MAX);
}
};