98. 验证二叉搜索树
-
有效二叉搜索树的定义
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。 -
解题思路
- 因为二叉搜索树的特性,一定要想到中序遍历;
- 其次是要注意
不能单纯的比较左节点小于中间节点,右节点大于中间节点,而是左子树所有节点小于中间节点,右子树所有节点大于中间节点; - 递归解法需要注意,有布尔型返回值,所以遇到不符合条件的返回False,否则继续递归遍历下去。
-
代码如下:
递归法:class Solution(object): def __init__(self): self.maxValue = float('-inf') def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ #递归 使用中序 #终止条件 if not root: return True left = self.isValidBST(root.left)#左 #如果中根节点值是从小到大则继续,否则验证结果是False if root.val > self.maxValue:#中 self.maxValue=root.val else: return False right = self.isValidBST(root.right) #如果左右节点值相等,也是False if left == right: return False else: return True
递归+数组法:
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ res=[] self.get_array(root,res) print(res) for i in ranage(1,len(res)): if res[i] <= res[i-1]: return False return True def get_array(self,root,res): #中序遍历 if root is None :return left = self.get_array(root.left,res) res.append(root.val) right = self.get_array(root.right,res)