[leetcode]Validate Binary Search Tree (判断有效二叉搜索树 C语言实现)

该博客介绍如何判断一个给定的二叉树是否为有效的二叉搜索树。利用中序遍历和链栈的方法,通过比较中序遍历过程中节点值的顺序来确定是否满足二叉搜索树的特性,即左子树节点小于根节点,根节点小于右子树节点。文章提供了一段C语言的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.
题意:判断一棵树是否满足二叉搜索树。
二叉搜索树的特点:左子树<根节点<右子树
解题思路:中序遍历,链栈,来实现。
对于一颗二叉树,中序遍历的结果若满足递增排序就满足二叉搜索树的条件,例如:
一颗二叉树如下:
二叉树
中序遍历的结果如下:1234567
中序遍历
正好满足二叉搜索树的条件,所以本题采用中序遍历的思路,把遍历的结果存储于链栈中,通过比较前后存入链栈的大小,来判断是否为二叉搜索树。
实现C代码如下:

/**
 *解题思路:中序遍历,链栈
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
  * };
 */
int flag;
struct Node{//创建一个链栈节点
    int val;
    struct Node *next;
};
struct Stack{//创建一个链栈
    struct Node *top;//指向链栈栈顶节点
    int count;//记录链栈的节点个数
};
void InitStack(struct Stack *stack){//初始化一个空栈
    stack->count = 0;
    stack->top = NULL;
}
void PushStack(struct Stack *stack,int val){//压栈
    struct Node *node;
    node = (struct Node *)malloc(sizeof(struct Node));
    if(stack->count > 0){
        if(stack->top->val < val){//若不是第一个进栈的节点,则判断与栈顶节点的值大小,若小于栈顶节点值则说明不是二叉搜索树
            node->val = val;
            node->next = stack->top;
            stack->top = node;
            stack->count++;
        }else{
            flag = -1;//若不是二叉搜索树设置全局标志位flag为-1;
            return;
        }
    }else{//第一个值进栈
        node->val = val;
        node->next = stack->top;
        stack->top = node;
        stack->count++;
    }
}
void Inorder(struct TreeNode *root,struct Stack *stack){//中序遍历
    if(root == NULL){
        return;
    }
    Inorder(root->left,stack);
    PushStack(stack,root->val);
    Inorder(root->right,stack);
}
bool isValidBST(struct TreeNode *root) {
    flag = 0;
    struct Stack *stack;
    stack = (struct Stack *)malloc(sizeof(struct Stack));
    InitStack(stack);
    Inorder(root,stack);
    if(flag == -1){
        return 0;
    }
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值