我用的递归,以为没问题,结果提交之后没通过!
仔细阅读才发现,题目我都没完全理解:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
比如:[10,5,15,null,null,6,20] 这个测试用例结果应该返回false,因为右子树中的左子节点6小于根节点10
我好傻呀
以下是看了题解之后再写的正解:
1、递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def helper(node, min_val, max_val):
if not node:
return True
if not (min_val < node.val < max_val):
return False
return helper(node.left, min_val, node.val) and helper(node.right, node.val, max_val)
return helper(root, float('-inf'), float('inf'))
2、二叉搜索树中序遍历之后是升序的,依照这个思路来:
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
min_val = float('-inf')
stack = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
top = stack.pop()
if top.val <= min_val:
return False
min_val = top.val
cur = top.right
return True