1 Star 0 Fork 0

ZechariahZheng / blog文档

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LeetCode_98 验证二叉搜索树.md 952 Bytes
一键复制 编辑 原始数据 按行查看 历史
ZechariahZheng 提交于 2020-01-15 09:16 . LeetCode_98 验证二叉搜索树

LeetCode_98 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1:

输入: 2 /
1 3 输出: true

思路:递归调用

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        if ((root.left!=null && root.left.val>=root.val)||
            (root.right!=null && root.right.val<=root.val)) {
            return false;
        }
        return isValidBST(root.left) && isValidBST(root.right);
    }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ZechariahZheng/blog_document.git
git@gitee.com:ZechariahZheng/blog_document.git
ZechariahZheng
blog_document
blog文档
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891