验证二叉搜索树
难度:中等
题目描述
给你一个二叉树的根节点 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);
}
}