力扣0098——验证二叉搜索树

文章介绍了如何通过回溯算法解决判断二叉树是否为有效二叉搜索树的问题,涉及到了递归遍历节点值、比较范围以及终止条件的处理。
摘要由CSDN通过智能技术生成

验证二叉搜索树

难度:中等

题目描述

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

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

示例1

输入: root = [2,1,3]
输出: true

示例2

输入: root = [5,1,4,null,null,3,6]
输出: false

题解

由题意得需要使用回溯法解题,使用以下步骤

  • 当回溯到根节点为空,返回true
  • 当回溯到根节点比最小值要小,返回false
  • 当回溯到根节点比最大值要大,返回false

遍历结束之后返回最终回溯的结果即为所得

想法代码

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution
{
    public static void Main(String[] args)
    {
        TreeNode treeNode = new TreeNode(2)
        {
            left = new TreeNode(1),
            right = new TreeNode(3)
        };
        Solution solution = new Solution();
        Console.WriteLine(solution.IsValidBST(treeNode));
    }

    public bool IsValidBST(TreeNode root)
    {
        return BackTrack(root, null, null);
    }

    public bool BackTrack(TreeNode root, int? min, int? max)
    {
        if (root == null)
        {
            return true;
        }

        if (min != null && root.val <= min)
        {
            return false;
        }

        if (max != null && root.val >= max)
        {
            return false;
        }
        return BackTrack(root.left,min,root.val) && BackTrack(root.right,root.val,max);
    }
}
oot.val) && BackTrack(root.right,root.val,max);
    }
}
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值