Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
分析:根据BST中序遍历序列有序的性质判断,只要在中序遍历二叉树的代码基础上加上判断相邻元素关系的语句即可
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//注意题目要求是 less than和greater than;
stack<TreeNode*> S;
TreeNode *pre = NULL, *p = root;
while(p || S.empty() == false)
{
while(p)
{
S.push(p);
p = p->left;
}
if(S.empty() == false)
{
p = S.top();
S.pop();
if(pre && p->val <= pre->val)return false;
pre = p;
p = p->right;
}
}
return true;
}
};
另外一种方法是判断1.当前节点左子树的最大值是否小于当前节点值2.当前节点右子树的最小值是否大于当前节点值。如果两个条件都满足,则是二叉搜索树。
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL|| root->left==NULL&&root->right==NULL)
return true;
TreeNode* left, *right;
bool ifValid=true;
if (root->left != NULL) {
left=root->left;
while (left->right!=NULL) {
left = left->right;
}
if(root->val>left->val) {
ifValid = isValidBST(root->left);
} else {
return false;
}
}
if(root->right != NULL) {
right = root->right;
while (right->left != NULL) {
right = right->left;
}
if (root->val<right->val) {
ifValid= ifValid&&isValidBST(root->right);
} else {
return false;
}
}
return ifValid;
}
};
2015.9.13更新
不用设置lastNum与ifFirst变量。直接用一个pre指针就好了。
---------------------------
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* p = root;
stack<TreeNode*> st;
TreeNode* pre = NULL;
while (p||!st.empty()) {
while (p) {
st.push(p);
p = p->left;
}
TreeNode* top = st.top();
st.pop();
if (pre&&top->val<=pre->val) {
return false;
}
pre = top;
p = top->right;
}
return true;
}
};