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.
鉴定一颗树是否是二叉搜索树。思路:
1)左子树最大点小于根节点,根节点小于右子树最小节点。
2)中序遍历是有序的。
思路1:
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
if((root->left==NULL||Max(root->left)<root->val)&&(root->right==NULL||Min(root->right)>root->val))
return isValidBST(root->left)&&isValidBST(root->right);
else
return false;
}
int Max(TreeNode *temp){
if(temp->right==NULL)
return temp->val;
else return Max(temp->right);
}
int Min(TreeNode *temp){
if(temp->left==NULL)
return temp->val;
else return Min(temp->left);
}
思路2:class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
vector<int> temp;
search(root,temp);
if(temp.size()==1)
return true;
for(int i=0; i<temp.size()-1; ++i){
if(temp[i]>=temp[i+1])
return false;
}
return true;
}
void search(TreeNode* root,vector<int> &temp){
if(root->left == NULL&&root->right==NULL){
temp.push_back(root->val);
return;
}
if(root->left)
search(root->left,temp);
temp.push_back(root->val);
if(root->right)
search(root->right,temp);
}
};