解题思路
-
二叉搜索树的特点
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉搜索树
**注意:**二叉搜索树不能单纯看左结点小于中间结点,右孩子大于中间结点,强调的是左子树的所有结点小于中间结点,右子树所有结点大于中间结点 -
根据二叉搜索树的特点,可以想到如果将二叉搜索树按中序遍历排列,那么应该是一个递增序列。所以可以按中序遍历将该树的结点存入一个数组,然后遍历数组,当前一个大于或等于后一个时,就返回false.
-
那么解题的关键在于怎么写中序遍历:(1)迭代法(2)递归法
递归法:
(1)确定递归终止条件:当传入结点为空时,停止并返回空结点
(2)单层递归逻辑:先遍历左子树,再传入中间结点,再遍历右子树
(3)void函数,无返回值
class Solution {
public:
vector<int> temp;
void travalsal(TreeNode* root){
if(!root)return ;
travalsal(root->left);
temp.push_back(root->val);
travalsal(root->right);
}
bool isValidBST(TreeNode* root) {
if(!root)return true;
travalsal(root);
for(int i=1;i<temp.size();i++){
if(temp[i]<=temp[i-1])return false;
}
return true;
}
};
迭代法(这里用了统一迭代法,利用null标记中间结点):
按照 右孩子,中间结点,null,左孩子入栈,当cur指向null,就出栈两次,弹出null,和 中间结点(压入结果数组里)。
class Solution {
public:
vector<int> travalsal(TreeNode* root){
//迭代法写中序遍历(统一迭代法)
if(!root)return {};
stack<TreeNode*> st;
vector<int> res;
st.push(root);
while(!st.empty()){
TreeNode* cur=st.top();
if(cur){
st.pop();
if(cur->right)st.push(cur->right);//右
st.push(cur);
st.push(nullptr);//中
if(cur->left)st.push(cur->left);//左
}
else{
st.pop();
cur=st.top();
res.push_back(cur->val);
st.pop();
}
}
return res;
}
bool isValidBST(TreeNode* root) {
if(!root)return true;
vector<int>temp=travalsal(root);
for(int i=1;i<temp.size();i++){
if(temp[i]<=temp[i-1])return false;
}
return true;
}
};
纯迭代法
class Solution {
public:
bool isValidBST(TreeNode* root) {
//迭代法写中序遍历(统一迭代法)
if(!root)return {};
stack<TreeNode*> st;
vector<int> res;
st.push(root);
TreeNode* low=nullptr;
TreeNode* fast=root;
while(!st.empty()){
TreeNode* cur=st.top();
if(cur){
st.pop();
if(cur->right)st.push(cur->right);//右
st.push(cur);
st.push(nullptr);//中
if(cur->left)st.push(cur->left);//左
}
else{
//设置前后指针,指针不要指着空结点:按右、中、左入栈,弹出来就是左、中、右(左小右大),要是fast指针在前,low指向fast的前一个点,所以fast值应大于low的值
st.pop();
cur=st.top();
fast=cur;
if(low && fast->val<=low->val)return false;
low=fast;
st.pop();
}
}
return true;
}
};