0098. Validate Binary Search Tree

98. Validate Binary Search Tree #

Problem #

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Problem Summary #

Given a binary tree, determine whether it is a valid binary search tree. Assume a binary search tree has the following characteristics:

  • The left subtree of a node contains only numbers less than the current node.
  • The right subtree of a node contains only numbers greater than the current node.
  • All left subtrees and right subtrees themselves must also be binary search trees.

Solution Ideas #

  • To determine whether a tree is a BST, simply judge recursively according to the definition

Code #


package leetcode

import "math"

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

// Solution 1: directly compare values according to the definition; values smaller than the root node are on the left, and values greater than the root node are on the right
func isValidBST(root *TreeNode) bool {
	return isValidbst(root, math.Inf(-1), math.Inf(1))
}
func isValidbst(root *TreeNode, min, max float64) bool {
	if root == nil {
		return true
	}
	v := float64(root.Val)
	return v < max && v > min && isValidbst(root.Left, min, v) && isValidbst(root.Right, v, max)
}

// Solution 2: output the BST into an array in left-root-right order; if it is a BST, the numbers in the array are sorted from smallest to largest; if a reverse order appears, it is not a BST
func isValidBST1(root *TreeNode) bool {
	arr := []int{}
	inOrder(root, &arr)
	for i := 1; i < len(arr); i++ {
		if arr[i-1] >= arr[i] {
			return false
		}
	}
	return true
}

func inOrder(root *TreeNode, arr *[]int) {
	if root == nil {
		return
	}
	inOrder(root.Left, arr)
	*arr = append(*arr, root.Val)
	inOrder(root.Right, arr)
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文