-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added the new question for validating binary search tree
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
Twopointer/Binary search/Linked List/Trees/98. Validate Binary Search Tree.py
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
'''98. Validate Binary Search Tree | ||
Medium | ||
Given the root of a binary tree, determine if it is a valid binary search tree (BST). | ||
A valid BST is defined as follows: | ||
The left | ||
subtree | ||
of a node contains only nodes with keys less than the node's key. | ||
The right subtree of a node contains only nodes with keys greater than the node's key. | ||
Both the left and right subtrees must also be binary search trees. | ||
Example 1: | ||
Input: root = [2,1,3] | ||
Output: true | ||
Example 2: | ||
Input: root = [5,1,4,null,null,3,6] | ||
Output: false | ||
Explanation: The root node's value is 5 but its right child's value is 4.''' | ||
|
||
# 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): | ||
def helper(node, lower=float('-inf'), upper=float('inf')): | ||
if not node: | ||
return True | ||
|
||
val = node.val | ||
if val <= lower or val >= upper: | ||
return False | ||
|
||
if not helper(node.right, val, upper): | ||
return False | ||
if not helper(node.left, lower, val): | ||
return False | ||
return True | ||
|
||
return helper(root) |