600 字
3 分钟
LeetCode-98.验证二叉搜索树
二叉树
给你一个二叉树的根节点
root,判断其是否是一个有效的二叉搜索树。有效 二叉搜索树定义如下:
- 节点的左子树只包含 严格小于 当前节点的数。
- 节点的右子树只包含 严格大于 当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
![]()
输入:root = [2,1,3]输出:true示例 2:
![]()
输入:root = [5,1,4,null,null,3,6]输出:false解释:根节点的值是 5 ,但是右子节点的值是 4 。
自己的解法
思路:从题目中可以看到二叉搜索树定义,
-
其中
isValidBST的递归,能够保证所有左子树和右子树自身必须也是二叉搜索树。 -
所以,我们只需要保证,本身的节点的大小能够比左边最大的大,比右边最小的小即可
我就是再来个递归获取最大和最小值
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */func isValidBST(root *TreeNode) bool { if root == nil { return true }
left := isValidBST(root.Left) leftmax := findmax(root.Left)
right := isValidBST(root.Right) rightmin := findmin(root.Right)
if leftmax != nil && rightmin != nil { if leftmax.Val >= root.Val || root.Val >= rightmin.Val { return false } }else if leftmax == nil && rightmin != nil { if root.Val >= rightmin.Val { return false } }else if leftmax != nil && rightmin == nil { if root.Val <= leftmax.Val { return false } }
return left && right}
func findmax(root *TreeNode) *TreeNode { if root == nil { return nil }
if root.Right == nil { return root }
return findmax(root.Right)}
func findmin(root *TreeNode) *TreeNode { if root == nil { return nil }
if root.Left == nil { return root }
return findmin(root.Left)}设定上下边界法
思路:给我的方法优化了一下
func isValidBST(root *TreeNode) bool { return validate(root, math.MinInt, math.MaxInt)}
func validate(node *TreeNode, min, max int) bool { if node == nil { return true }
if node.Val <= min || node.Val >= max { return false }
leftValid := validate(node.Left, min, node.Val)
rightValid := validate(node.Right, node.Val, max)
return leftValid && rightValid}中序遍历法
思路:二叉搜索树进行中序遍历,得到的结果一定是一个「严格递增」的有序序列
所以只需要进行中序遍历,再比较大小即可
func isValidBST(root *TreeNode) bool { preVal := math.MinInt
var inorder func(*TreeNode) bool inorder = func(node *TreeNode) bool { if node == nil { return true }
leftValid := inorder(node.Left)
if node.Val <= preVal { return false } preVal = node.Val
rightValid := inorder(node.Right)
return leftValid && rightValid }
return inorder(root)} LeetCode-98.验证二叉搜索树
https://sheep44044.github.io/posts/算法/二叉树/leetcode-98验证二叉搜索树/