LeetCode-98-验证二叉树

  |   0 评论   |   0 浏览

题目

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

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

输入:
    2
   / \
  1   3
输出: true
示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

解法

比较巧妙的写法:go实现,maxInt64是因为测试用例有int64的值

package main

func isValidBST(root *TreeNode) bool {

	return validate(root, math.MinInt64, math.MaxInt64)
}

func validate(node *TreeNode, min int, max int) bool {
	if node == nil {
		return true
	}

	if node.Val <= min || node.Val >= max {
		return false
	}
	return validate(node.Left, min, node.Val) && validate(node.Right, node.Val, max)
}

image.png


标题:LeetCode-98-验证二叉树
作者:guobing
地址:http://guobingwei.tech/articles/2020/10/22/1603334544541.html