给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
static void DFS(struct TreeNode* root,bool *ret,int min,int max,unsigned char flag)
{
if(!(*ret)||!root)return;
if(flag==1)
{//左子树
if(root->val>=max)*ret=false;
DFS(root->left,ret,0,root->val,1);
DFS(root->right,ret,root->val,max,0);
}
else if(flag==2)
{//右子树
if(root->val<=min)*ret=false;
DFS(root->left,ret,min,root->val,0);
DFS(root->right,ret,root->val,0,2);
}
else
{
if(root->val>=max||root->val<=min)*ret=false;
DFS(root->left,ret,min,root->val,0);
DFS(root->right,ret,root->val,max,0);
}
}
bool isValidBST(struct TreeNode* root){
if(!root)return true;
bool ret=true;
DFS(root->left,&ret,0,root->val,1);
DFS(root->right,&ret,root->val,0,2);
//printf("%d \n",ret);
return ret;
}
执行用时 : 24 ms, 在Validate Binary Search Tree的C提交中击败了69.71% 的用户
内存消耗 : 10 MB, 在Validate Binary Search Tree的C提交中击败了100.00% 的用户