解题思路
中序遍历二叉树,检查结果是否为递增序列,若是则为二叉搜索树。
代码
class Solution {
public:
void inorder(TreeNode *root,vector<int> &res){
if(root != NULL){
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
}
bool isValidBST(TreeNode *root) {
if(root == NULL)
return true;
vector<int>res;
inorder(root,res);
bool flag = true;
int len = res.size();
for(int i = 1;i < len;i++)
if(res[i] <= res[i - 1]){
flag = false;
break;
}
return flag;
}
};