给定一个二叉树根节点,请你判断这棵树是不是二叉搜索树。
二叉搜索树满足每个节点的左子树上的所有节点均小于当前节点且右子树上的所有节点均大于当前节点。
例:
图1
图2
数据范围:节点数量满足 ,节点上的值满足
#include <stdbool.h> #include <limits.h> bool isValidBSTHelper(struct TreeNode* root, long min, long max) { if (root == NULL) { return true; } if (root->val <= min || root->val >= max) { return false; } return isValidBSTHelper(root->left, min, root->val) && isValidBSTHelper(root->right, root->val, max); } bool isValidBST(struct TreeNode* root) { return isValidBSTHelper(root, LONG_MIN, LONG_MAX); }
bool isValidBSTMaxMin(struct TreeNode* root , int *Min, int *Max) { int LeftMin, LeftMax, RightMin, RightMax; bool LeftReturn, rightRturn; if(root==NULL) return true; *Min = root->val; *Max = root->val; if(root->left!=NULL) { LeftReturn=isValidBSTMaxMin(root->left, &LeftMin, &LeftMax); *Min = LeftMin > *Min ? *Min : LeftMin; *Max = LeftMax > *Max ? LeftMax : *Max; } if(root->right!=NULL) { rightRturn=isValidBSTMaxMin(root->right, &RightMin, &RightMax); *Min = RightMin > *Min ? *Min : RightMin; *Max = RightMax > *Max ? RightMax : *Max; } if(root->left!=NULL) if((LeftReturn==false) || (LeftMax >= root->val)) return false; if(root->right!=NULL) if((rightRturn==false) || (RightMin <= root->val)) return false; return true; } bool isValidBST(struct TreeNode* root ) { int Min, Max; return isValidBSTMaxMin(root, &Min, &Max); }
static bool isValidBST_helper(TNode *root, int lower, int upper) { if (root == NULL) return true; int val = root->val; if (val > upper||val < lower) return false; return isValidBST_helper(root->left, lower,val)&&isValidBST_helper(root->right, val,upper); } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @param root TreeNode类 * @return bool */ bool isValidBST(struct TreeNode* root) { if (root == NULL) return true; return isValidBST_helper(root, INT32_MIN+1, INT32_MAX-1); }
#include <stdbool.h> struct TreeNode* tree(struct TreeNode* root,int flag){ if(root == NULL){ return NULL; } struct TreeNode* left = NULL; struct TreeNode* right= NULL; if(root->left!=NULL){ if(root->left->val>root->val){ return NULL; } left = tree(root->left,1); if(left==NULL){ return NULL; } if(left->val>root->val){ return NULL; } } if(root->right!=NULL){ if(root->right->val<root->val){ return NULL; } right = tree(root->right,0); if(right==NULL){ return NULL; } if(right->val<root->val){ return NULL; } } if(flag!=2&&left==NULL&&right==NULL){ return root; } if(flag == 0&&left!=NULL){ return left; }if(flag==1&&right!=NULL){ return right; } return root; } bool isValidBST(struct TreeNode* root ) { if(root==NULL){ return true; } else if(tree(root,2)==NULL){ return false; } return true; }
int max = 0; bool turn = false; bool check(struct TreeNode* root){ if(!root) return true; bool a = check(root->left); if(!turn) turn = true, max = root->val; else if(root->val < max) return false; else max = root->val; bool b = check(root->right); return a&&b; } bool isValidBST(struct TreeNode* root ) { // write code here return check(root); }