LeetCode(力扣)98. 验证二叉搜索树Python

LeetCode98. 验证二叉搜索树

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/validate-binary-search-tree/
LeetCode(力扣)98. 验证二叉搜索树Python_第1张图片

代码

递归

# 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 False
        return 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 = root
        pre = None
        while cur is not None or len(stack) > 0:
            if cur is not None:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if pre is not None and cur.val <= pre.val:
                    return False
                pre = cur
                cur = cur.right
        return True

你可能感兴趣的:(leetcode,python,算法,职场和发展)