方法一:判断每一个结点,必定存在该结点的值大于左子树的最大值,小于右子树的最小值
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
#include <limits.h>
#include <stdbool.h>
bool isValidBSTFunc(struct TreeNode* root, int l, int r) {
if (root == NULL) {
return true;
}
if (l > root->val || root->val > r) {
return false;
}
return isValidBSTFunc(root->left, l, root->val)&&isValidBSTFunc(root->right, root->val, r);
}
bool isValidBST(struct TreeNode* root ) {
// write code here
return isValidBSTFunc(root, INT_MIN, INT_MAX);
}
方法二:中序遍历二叉树,将结点放入数组内,判断是否为升序数组
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
void inOrderTraversal(struct TreeNode* root, int *ret, int* returnSize){
if(!root) return ;
inOrderTraversal(root->left,ret,returnSize);
ret[(*returnSize)++]=root->val;
inOrderTraversal(root->right,ret,returnSize);
}
bool isValidBST(struct TreeNode* root ) {
// write code here
int* ret=(int*)malloc(sizeof(int)*10000000);
int returnSize=0;
inOrderTraversal(root,ret,&returnSize);
for(int i=0;i<returnSize-1;i++){
if(ret[i]>ret[i+1]) {return false;}
}
return true;
}