//判断是否为BST 搜索树==二叉排序树 1、递归知最大最小值。2、先中序判是否单调 bool IsValidBST(BTNode *p,int low,int high){ if(p==NULL){ return true; }else{ if(low<p->data && high>p->data){ return(IsValidBST(p->lchild,low,high) && IsValidBST(p->rchild,low,high)); }else{ return false; } } } void IsBST(BTNode *p,int &k,bool &fail){ if(p && !fail){ IsBST(p->lchild,k,fail); if(k<p->data){ k=p->data; }else{ fail=true; } IsBST(p->rchild,k,fail); } }
bool isValidBST(TreeNode *root) { vector<int> res; isValidBST(root, res); int len = res.size(); bool flag = true; for (int i=0; i<len-1; i++){ if (res[i] >= res[i+1]){ flag = false; break; } } return flag; } void isValidBSTOrder(TreeNode *root, vector<int> &res){ if (root == NULL) return; isValidBST(root->left, res); res.push_back(root->val); isValidBST(root->right, res); }
//判断是否为BST bool fail=false; void IsBST(BTNode *p,int &k,bool &fail){ if(p && !fail){ IsBST(p->lchild,k,fail); if(k<p->data){ k=p->data; }else{ fail=true; } IsBST(p->rchild,k,fail); } }