Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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:
- if not root:
- return True
- # if left and right node exists ret=True
- ret = bool(root.left) == bool(root.right) and root.right
- # so if both the node exists check the base condition and store AND of it
- if ret:
- ret = root.left.val < root.val and (root.right.val > root.val)
- # ret is false and
- elif root.right != root.left:
- #this was added for edge cases
- if root.right:
- return root.right.val == -1
- if root.left:
- return root.left.val == -1
- #===============================
- return False
- else:
- return True
- # now ret is true
- return ret and self.isValidBST(root.left) and self.isValidBST(root.right)
Add Comment
Please, Sign In to add comment