Skip to content

binary tree - max depth | valid bst #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 21, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
added validate bst
  • Loading branch information
mihirs16 committed May 21, 2022
commit d2800ac3a121314aeb157a6dc316ad551b4ae9ed
36 changes: 36 additions & 0 deletions 14. Questions/leetcode 98 - validate binary search tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# validate binary search tree | leetcode 98 | https://leetcode.com/problems/validate-binary-search-tree/
# Given the root of a binary tree, determine if it is a valid binary search tree (BST).
# method: in-order traversal of a valid bst gives a sorted array
# tip: use `prev` pointer instead of an array to keep space complexity as O(1)

# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:

# initialise a prev pointer
def __init__(self):
self.prev = None

# in-order traversal (L M R)
# should return a sorted array
def isValidBST(self, root) -> bool:

# if this node is none, its a leaf
if root is None:
return True

if not self.isValidBST(root.left):
return False

if self.prev is not None and self.prev.val >= root.val:
return False

self.prev = root

return self.isValidBST(root.right)