LeetCode98. 验证二叉搜索树
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/validate-binary-search-tree/
代码
递归
# 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 __init__(self):self.vec = []def traversal(self, root):if root is None:return self.traversal(root.left)self.vec.append(root.val)self.traversal(root.right)def isValidBST(self, root: Optional[TreeNode]) -> bool:self.vec = []self.traversal(root)for i in range(len(self.vec) - 1):if self.vec[i] >= self.vec[i + 1]:return Falsereturn True
字典
# 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:stack = []cur = rootpre = Nonewhile cur is not None or len(stack) > 0:if cur is not None:stack.append(cur)cur = cur.leftelse:cur = stack.pop()if pre is not None and cur.val <= pre.val:return Falsepre = curcur = cur.rightreturn True