给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
code:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
long preVisit=LONG_MIN;//int有边界值
public:
bool isValidBST(TreeNode* root) {
if(root==nullptr)//不加||(root->left==nullptr&&root->right==nullptr),因为遍历到叶子结点时不会更新perVisit值
return true;
bool Res=true;
Res=Res&&isValidBST(root->left);
if(preVisit<root->val)
preVisit=root->val;
else
Res=false;
Res=Res&&isValidBST(root->right);
return Res;
}
};
code:非递归(中序遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode* pre;
public:
bool isValidBST(TreeNode* root) {
if(root==nullptr)
return true;
stack<TreeNode*> stack;
TreeNode* cur=root;
while(cur||!stack.empty())
{
if(cur)
{
stack.push(cur);
cur=cur->left;
}
else
{
cur=stack.top();
stack.pop();
if(pre&&pre->val>=cur->val)
return false;
pre=cur;
cur=cur->right;
}
}
return true;
}
};
来源:https://www.cnblogs.com/tianzeng/p/12349521.html