代码拉取完成,页面将自动刷新
# Time: O(n)
# Space: O(1)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Morris Traversal Solution
class Solution(object):
# @param root, a tree node
# @return a list of integers
def isValidBST(self, root):
prev, cur = None, root
while cur:
if cur.left is None:
if prev and prev.val >= cur.val:
return False
prev = cur
cur = cur.right
else:
node = cur.left
while node.right and node.right != cur:
node = node.right
if node.right is None:
node.right = cur
cur = cur.left
else:
if prev and prev.val >= cur.val:
return False
node.right = None
prev = cur
cur = cur.right
return True
# Time: O(n)
# Space: O(h)
class Solution2(object):
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
return self.isValidBSTRecu(root, float("-inf"), float("inf"))
def isValidBSTRecu(self, root, low, high):
if root is None:
return True
return low < root.val and root.val < high \
and self.isValidBSTRecu(root.left, low, root.val) \
and self.isValidBSTRecu(root.right, root.val, high)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。