题目
思路
拆解子问题。
找到左子树和右子树中最大值和最小值,和根节点进行比较。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of binary tree.
@return: True if the binary tree is BST, or false
"""
def bfs(self, root):
if not root.left and not root.right:
return True, root.val, root.val
leftValid, rightValid = True, True
if root.left:
leftValid, leftMin, leftMax = self.bfs(root.left)
if root.right:
rightValid, rightMin, rightMax = self.bfs(root.right)
if not leftValid or not rightValid:
return False, 0, 0
if root.left and root.right and leftValid and rightValid:
if leftMax < root.val and root.val < rightMin:
return True, leftMin, rightMax
elif root.left and leftValid:
if leftMax < root.val: return True, leftMin, root.val
elif root.right and rightValid:
if root.val < rightMin: return True, root.val, rightMax
return False, 0, 0
def isValidBST(self, root):
# write your code here
if not root:
return True
return self.bfs(root)[0]