98. 验证二叉搜索树
问题描述
https://leetcode.cn/problems/validate-binary-search-tree/description/
解题思路
二叉搜索树的性质是:root节点要大于左子树的最大值,小于右子树的最小值。
同时,对上层,也要更新本层的最大值和最小值以供继续递归。
补充:二叉搜索树的中序遍历其实是有序的。根据这点,我们可以用一个数组轻松搞定。详见“代码补充”
代码
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: flag = True def dfs(root): if root is None: return None, None left_min, left_max = dfs(root.left) right_min, right_max = dfs(root.right) nonlocal flag if not flag: return None, None mins, maxs = root.val, root.val if left_max and left_max < root.val: mins = left_max elif left_max: flag = False if right_min and right_min > root.val: maxs = right_min elif right_min: flag = False if left_min: mins = min(left_min, mins) if right_max: maxs = max(maxs, right_max) return mins, maxs dfs(root) return flag
代码补充
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: li = [] def dfs(root): if root is None: return dfs(root.left) li.append(root.val) dfs(root.right) dfs(root) return li == sorted(li) and set(li).__len__() == len(li)
2024二刷:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: return self.dfs(root)[2] def dfs(self, root): if root is None: return None, None, True if root.left is None and root.right is None: return root.val, root.val, True l_min, l_max, l_flag = self.dfs(root.left) r_min, r_max, r_flag = self.dfs(root.right) last_result = l_flag and r_flag cur_min, cur_max = root.val, root.val if root.left: last_result = last_result and l_max < root.val cur_min = min(l_min, cur_min) cur_max = max(l_max, cur_max) if root.right: last_result = last_result and root.val < r_min cur_min = min(r_min, cur_min) cur_max = max(r_max, cur_max) return cur_min, cur_max, last_result