1. 题目描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/
1 3
输出: true
示例 2:
输入:
5
/
1 4
/
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码如下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct TreeNode Node;
//分别计算左右子树的最小值和最大值
int calcMaxValueInTree(Node *root)
{
int max = root->val;
if(root->left != NULL)
{
int maxleft = calcMaxValueInTree(root->left);
max = max > maxleft?max:maxleft;
}
if(root->right != NULL)
{
int maxright = calcMaxValueInTree(root->right);
max = max > maxright?max:maxright;
}
return max;
}
int calcMinValueInTree(Node *root)
{
int min = root->val;
if(root->left != NULL)
{
int minleft = calcMinValueInTree(root->left);
min = min < minleft?min:minleft;
}
if(root->right != NULL)
{
int minright = calcMinValueInTree(root->right);
min = min < minright?min:minright;
}
return min;
}
bool isValidBST(struct TreeNode* root) {
if(!root)
{
return true;
}
if(root->left != NULL&&calcMaxValueInTree(root->left) >= root->val)
{
return false;
}
if(root->right != NULL&&calcMinValueInTree(root->right) <= root->val)
{
return false;
}
return isValidBST(root->left)&&isValidBST(root->right);
}
//2021-03-18
//使用LDR遍历二叉树得到序列,若序列值递增,则是合格的二叉搜索树
typedef struct TreeNode Node;
typedef struct st_stack
{
Node *array[10000];//节点指针数组,用于存放二叉树的节点指针
int top;
int tail;
int size;
}STACK;
//栈初始化
void stack_init(STACK *pstack)
{
if (pstack == NULL)
{
return;
}
memset(pstack,0,sizeof(STACK));
}
//元素入栈
void in_stack(STACK *pstack,Node *pnode)
{
pstack->array[pstack->top] = pnode;
pstack->top++;
pstack->size++;
}
//判断栈是否为空
bool stack_empty(STACK *pstack)
{
if (pstack->size == 0)
{
return true;
}
return false;
}
//出栈--栈顶元素出栈
Node* out_stack(STACK *pstack)
{
Node* ptmp = pstack->array[pstack->top-1];
pstack->top--;
pstack->size--;
return ptmp;
}
STACK g_stack;
bool isValidBST(struct TreeNode* root){
Node *parray[10000] = {0};
int node_count = 0;
Node *ptmp = root;
stack_init(&g_stack);
while (ptmp || stack_empty(&g_stack) == false)
{
while (ptmp)
{
in_stack(&g_stack,ptmp);
ptmp = ptmp->left;
}
ptmp = out_stack(&g_stack);
if (ptmp)
{
parray[node_count] = ptmp;
node_count += 1;
ptmp = ptmp->right;
}
}
for (int i = 1 ;i < node_count;i++)
{
if (parray[i]->val <= parray[i-1]->val)
{
return false;
}
}
return true;
}