1、题目描述
输入一棵二叉树,判断它是否是BST。
2、思路
中序排序。判断是否后一个元素一直大于前一个元素。
3、代码
bool isValidBST(TreeNode* root) {
vector<int>v;
inorder(root,v);
for(int i=1;i<v.size();i++){
if(v[i]<=v[i-1]) return false;
}
return true;
}
void inorder(TreeNode* root,vector<int>&v){
if(!root) return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
class Solution {
public:
bool isValidBST(TreeNode* root) {
return helper(root, NULL, NULL);
}
bool helper(TreeNode* root, TreeNode* minn, TreeNode* maxx) {
if(root == NULL)
return true;
if(minn != NULL && root->val <= minn->val)
return false;
if(maxx != NULL && root->val >= maxx->val)
return false;
return helper(root->left, minn, root) && helper(root->right, root, maxx);
}
};