[LeetCode] 98. Validate Binary Search Tree(验证二叉搜索树)
-
Difficulty: Medium
-
Related Topics: Tree, Depth-first Search, Recursion
-
Link: https://leetcode.com/problems/validate-binary-search-tree/
Description
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
给定二叉树的根 root
,判断其是否为合法的二叉搜索树(BST)。
A valid BST is defined as follows:
一颗合法的 BST 满足以下条件:
- 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.
任意节点的左右子树也必须是 BST。
Examples
Example 1
Input: root = [2,1,3]
Output: true
Example 2
Input: root = [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.
Constraints
- The number of nodes in the tree is in the range
[1, 1e4]
. -2^31 <= Node.val <= 2^31 - 1
Solution
本来想着利用题目给的二叉树的递归定义解题,然后以此思路写的代码全部 WA,于是先用以下暴力方法先过了,意外地效果还可以。代码如下:
class Solution {
private val list = arrayListOf<Int>()
fun isValidBST(root: TreeNode?): Boolean {
list.clear()
inOrder(root)
return list.isSorted()
}
private fun inOrder(root: TreeNode?) {
if (root != null) {
inOrder(root.left)
list.add(root.`val`)
inOrder(root.right)
}
}
private fun List<Int>.isSorted(): Boolean {
if (this.size < 2) {
return true
}
for (i in 0 until this.lastIndex) {
if (this[i] >= this[i + 1]) {
return false
}
}
return true
}
}
那么这题真正的递归解法长啥样?我在 discussion 里找到了一个刷新我的三观的解法,其主要思路用一句话概括就是:遍历树的同时,维护一个区间 minVal, maxVal
,节点值必须在该区间范围内。代码如下:
class Solution {
fun isValidBST(root: TreeNode?): Boolean {
return isValidBst(root, Long.MIN_VALUE, Long.MAX_VALUE)
}
private fun isValidBst(root: TreeNode?, minVal: Long, maxVal: Long): Boolean {
if (root == null) {
return true
}
if (root.`val` >= maxVal || root.`val` <= minVal) {
return false
}
return isValidBst(root.left, minVal, root.`val`.toLong()) &&
isValidBst(root.right, root.`val`.toLong(), maxVal)
}
}