【leetcode】Validate Binary Search Tree

时间:2021-11-20 08:12:47

Validate Binary Search Tree

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 
思路一:利用递归的思想,任何一个节点必须要在min和max范围内
 
min和max根据是左子树还是右子树来确定
 
如果是左子树:
node->left<node
 
如果是右子树:
node->right>node
 
 
递归条件:node->val在min和max范围内,node->left要在min,node->val范围内,node->right要在node->val,max范围内
node->val<max&&node->val>min&&testValid(node->left,node->val,min)&&testValid(node->right,max,node->val); 
 
 
 
 /**
* 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) { if(root==NULL)
{
return true;
} if(root->left==NULL&&root->right==NULL)
{
return true;
} //注意如果测试用例含有INT_MAX则,必须采用long long int 才能避免出错
return testValid(root,(long long int)INT_MAX+,(long long int)INT_MIN-);
} bool testValid(TreeNode *node,long long int max, long long int min)
{
if(node==NULL)
{
return true;
} return node->val<max&&node->val>min&&testValid(node->left,node->val,min)&&testValid(node->right,max,node->val); }
};
 
 
 
第二种方法,利用 二叉排序树 中序遍历 结果为递增序列的性质
 
 
 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> ret_v;
bool isValidBST(TreeNode *root) { if(root==NULL)
{
return true;
} ret_v.clear();
inOrderTraversal(root); //判断是否递增
for(int i=;i<ret_v.size()-;i++)
{
if(ret_v[i]>=ret_v[i+])
{
return false;
}
}
return true;
} //中序遍历,记录下数值
void inOrderTraversal(TreeNode *root)
{
if(root==NULL)
{
return;
} inOrderTraversal(root->left);
ret_v.push_back(root->val);
inOrderTraversal(root->right);
}
};
 
 
 
第三种:直接在中序遍历中判断:
 
 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public: int ret;
bool flag;
bool isFirstNode; bool isValidBST(TreeNode *root) { flag=true;
//判断是不是第一个被访问的节点
isFirstNode=true; inOrderTraversal(root);
return flag;
} void inOrderTraversal(TreeNode *root)
{
if(root==NULL)
{
return;
} if(!flag)
{
return;
} inOrderTraversal(root->left); //一旦发现不符合升序,则不是二叉排序树
if(!isFirstNode&&ret>=root->val)
{
flag=false;
return;
} ret=root->val;
isFirstNode=false; inOrderTraversal(root->right);
} };