// determines whether BST search tree binary sort tree == 1, recursive known maximum and minimum. 2, in order to judge whether or not monotonic BOOL IsValidBST (BTNode * P, int Low, int High) { IF (P == NULL) { return to true ; } the else { IF (Low <p-> High Data &&> p-> Data) { return (IsValidBST (p-> lchild, Low, High) && IsValidBST (P -> rchild, Low, High)); } the else { return to 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); } }