zero_shubham1

validST

Aug 20th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.left = None
  6. #         self.right = None
  7.  
  8. class Solution:
  9.     def isValidBST(self, root: TreeNode) -> bool:
  10.         if not root:
  11.             return True
  12.            
  13.         # if left and right node exists ret=True
  14.         ret = bool(root.left) == bool(root.right) and root.right
  15.        
  16.         #  so if both the node  exists check the base condition and  store  AND of it
  17.         if ret:
  18.             ret = root.left.val < root.val and  (root.right.val > root.val)
  19.         # ret is false and
  20.         elif root.right != root.left:
  21.             #this was added for edge cases
  22.             if root.right:
  23.                 return root.right.val == -1
  24.             if root.left:
  25.                 return root.left.val == -1
  26.             #===============================
  27.             return False
  28.         else:
  29.             return True
  30.        
  31.         # now ret is true
  32.         return ret and self.isValidBST(root.left) and self.isValidBST(root.right)
Add Comment
Please, Sign In to add comment