验证二叉搜索树
描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/
1 3
输出: true
递归
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL || (root->left==NULL && root->right==NULL))
return true;
if(isValidBST(root->left))
{
if(root->left!=NULL)
{
int max = getMaxOfBST(root->left);
if(root->val <= max)
return false;
}
}
else
return false;
if(isValidBST(root->right))
{
if(root->right!=NULL)
{
int min = getMinOfTree(root->right);
if(root->val >= min)
return false;
}
}
else
return false;
return true;
}
int getMaxOfBST(TreeNode* root)
{
int max = root->val;
while(root!=NULL)
{
if(root->val >= max)
max = root->val;
root = root->right;
}
return max;
}
int getMinOfTree(TreeNode* root)
{
int min = root->val;
while(root!=NULL)
{
if(root->val<=min)
min = root->val;
root = root->left;
}
return min;
}
};
用栈
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == NULL)
return true;
stack<TreeNode*> s;
TreeNode* pre = NULL;
while(root!=NULL || !s.empty())
{
while(root!=NULL)
{
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
if(pre!=NULL && pre->val>=root->val)
return false;
pre = root;
root = root->right;
}
return true;
}
};
moris遍历
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (!root)
return true;
TreeNode *cur = root, *pre, *parent = NULL;//parent表示前一个结点,pre表示mostright
bool res = true;
while (cur) {
if (!cur->left) {
if (parent && parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
if (parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
}
}
}
return res;
}
};