参考官方解析
- 递归
# 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: TreeNode) -> bool:
def dfs(root,lower=float('-inf'), upper=float('inf')):
if not root: return True
return (lower < root.val < upper and dfs(root.left, lower, root.val) and dfs(root.right, root.val, upper))
return dfs(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: TreeNode) -> bool:
stack = []
pre = float('-inf')
while stack or root:
# 左子树的左节点一路入栈
while root:
stack.append(root)
root = root.left
# 检查
root = stack.pop()
if root.val <= pre: return False
# 更新下限
pre = root.val
# 右子树
root = root.right
return True