LeetCode98. 验证二叉搜索树Golang版
1. 问题描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
2. 思路
2.1. 递归
2.2. 迭代
中序遍历模板题
注意: 二叉搜索树中不能有相等的两个节点
3. 代码
3.1. 递归代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// var pre *TreeNode
func isValidBST(root *TreeNode) bool {
return isValid(root, math.MinInt64, math.MaxInt64)
}
func isValid(root *TreeNode, min int, max int) bool {
if root == nil {
return true
}
if root.Val <= min ||root.Val >= max{
return false
}
leftRes := isValid(root.Left, min, root.Val)
rightRes := isValid(root.Right, root.Val, max)
return leftRes && rightRes
}
3.2. 迭代(中序遍历)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// var pre *TreeNode
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
var stack []*TreeNode
var latestTop *TreeNode
node := root
for node != nil || len(stack) != 0 {
for node != nil {
stack = append(stack, node)
node = node.Left
}
top := stack[len(stack) - 1]
if latestTop != nil && top.Val <= latestTop.Val {
return false
}
latestTop = top
stack = stack[:len(stack) - 1]
node = top.Right
}
return true
}