Skip to content

Latest commit

 

History

History
32 lines (30 loc) · 1 KB

96. 验证二叉搜索树.md

File metadata and controls

32 lines (30 loc) · 1 KB

给你一个二叉树的根节点 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:
        #思路:利用栈做中序遍历,得到递增的数列则为二叉搜索树
        if not root:
            return False
        unused, used = 0,1
        stack = [(unused, root)]
        res = []

        while stack:
            state, node = stack.pop()
            if not node:
                continue
            if state == 0:
                stack.append((unused, node.right))
                stack.append((used, node))
                stack.append((unused, node.left))
            else:
                if res and res[-1] >= node.val:
                    return False
                res.append(node.val)
        return True