题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @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 returnSize=0;
int *ret=(int*)malloc(sizeof(int)*1000000);
inOrderTraversal(root, ret, &returnSize);
for(int i=0;i<returnSize-1;i++){
if(ret[i]>ret[i+1]){
return false;
}
}
return true;
}
先进行中序遍历,用数组将遍历结果存起来,判断一下数组是不是升序的。


查看1道真题和解析