Created
February 6, 2020 19:57
-
-
Save anilpai/9764b4b7ffeb124682c4cfcb13bef8ae to your computer and use it in GitHub Desktop.
Check if given Binary Tree is Binary Search Tree (BST) or not.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TreeNode: | |
| def __init__(self, value, left=None, right=None): | |
| self.value = value | |
| self.left = left | |
| self.right = right | |
| def __str__(self): | |
| return "(%s)"% (self.value) | |
| def isValidBST(root, min ,max): | |
| if root is None: | |
| return True | |
| if root.value <= min or root.value > max: | |
| return False | |
| return isValidBST(root.left, min, root.value) and isValidBST(root.right, root.value, max) | |
| t = TreeNode(10) | |
| t.left = TreeNode(10) | |
| t.left.left = TreeNode(-5) | |
| t.right = TreeNode(19) | |
| t.right.left = TreeNode(17) | |
| t.right.right = TreeNode(21) | |
| print(isValidBST(t, float('-inf') , float('inf'))) | |
| t1 = TreeNode(10) | |
| t1.left = TreeNode(0) | |
| t1.left.left = TreeNode(-1) | |
| t1.left.right = TreeNode(21) | |
| t1.right = TreeNode(25) | |
| t1.right.left = TreeNode(16) | |
| t1.right.right = TreeNode(32) | |
| print(isValidBST(t1, float('-inf'), float('inf'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment