1、题目描述
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.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
- Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.
2、问题描述:
- 有效的二叉搜索树,左子树的所有值小于根节点,右子树的所有结点值大于根节点。(记住是所有的哦),左右子树也都是二叉搜索树。
3、问题关键:
- 1.分别递归的求解左右子树是否是二叉搜索树。
- 2.递归的时候需要更新,左右子树的最大值和最小值。
- 3.记住要使用引用变量,记录最小值和最大值,值传递不可以。
4、C++代码:
class Solution {
public:
bool dfs(TreeNode* &root, int &maxv, int &minv) {//记得是引用传递。
if (!root) return true;
minv = maxv = root->val;
if (root->left) {
int nowmax, nowmin;
if (!dfs(root->left, nowmax, nowmin)) return false;
if (nowmax >= root->val) return false;//这个地方是可以大于maxv的,因为这个时候还么有更新maxv的值。
minv = nowmin;//如果左子树的是一个合法的,那么返回左边的最小值,因为左子树的最大值是小于当前结点的值。
}
if (root->right) {
int nowmax, nowmin;
if (!dfs(root->right, nowmax, nowmin)) return false;
if (nowmin <= root->val) return false;//这是小于等于root->val,因为上面会更新minv的值。
maxv = nowmax;
}
return true;
}
bool isValidBST(TreeNode* root) {
if (!root) return true;
int maxv, minv;
return dfs(root, maxv, minv);
}
};