题目:
验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4
思路:
左节小于根节点(小于最大值)且大于最小值。右节点大于根节(大于最小值)点且小于最大值。
每次进入左子树设定最大值,最小值不变。进入右子树设定最小值,最大值不变。
leetcode代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
long emmm(struct TreeNode* root,long max,long min){
int ld=1,rd=1;
if(root){
if(root->left!=NULL){
if(root->left->val>=root->val||root->left->val<=min)
return 0;
ld=emmm(root->left,root->val,min);//带入最大值
if(ld==0)
return 0;
}
if(root->right!=NULL){
if(root->right->val<=root->val||root->right->val>=max)
return 0;
rd=emmm(root->right,max,root->val);//带入追小值
if(rd==0)
return 0;
}
}
return 1;
}
bool isValidBST(struct TreeNode* root){
int r;
r=emmm(root,LONG_MAX,LONG_MIN);
return r;
}
leetcode参考daan:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int CheckValidSubTree(struct TreeNode *node, long low, long high)
{
int res;
if (node == NULL) {
return 1;
}
// printf("check for node %d low %d high %d\n", node->val, low, high);
if ((node->val <= low) || (node->val >= high)) {
// printf("unexpced happen\n");
return 0;
}
res = CheckValidSubTree(node->left, low, node->val);
if (res == 0) {
return 0;
}
res = CheckValidSubTree(node->right, node->val, high);
return res;
}
bool isValidBST(struct TreeNode* root)
{
int res;
res = CheckValidSubTree(root, LONG_MIN, LONG_MAX);
return res ? true : false;
}