三种解法:1,递归,2.迭代,3,中序遍历(二叉搜索树的中序遍历是一个递增数列)
1.递归
func isValidBST(root *TreeNode) bool {
return helper(root, math.MinInt64, math.MaxInt64)
}
func helper(root *TreeNode, lower, upper int) bool {
if root == nil {
return true
}
if root.Val <= lower || root.Val >= upper {
return false
}
return helper(root.Left, lower, root.Val) && helper(root.Right, root.Val, upper)
}
本文介绍了如何使用递归和迭代两种方法验证一个二叉树是否为有效的二叉搜索树。递归解法通过辅助函数实现,迭代解法则利用了二叉搜索树中序遍历的特性。这两种方法都确保了树中每个节点的值在给定范围内。
632

被折叠的 条评论
为什么被折叠?



