Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f78842a

Browse files
#98: Validate Binary Search Tree
1 parent f36617c commit f78842a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎Trees/is_valid_bst.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Given the root of a binary tree, determine if it is a valid binary search tree (BST).
2+
3+
# A valid BST is defined as follows:
4+
5+
# The left subtree of a node contains only nodes with keys less than the node's key.
6+
# The right subtree of a node contains only nodes with keys greater than the node's key.
7+
# Both the left and right subtrees must also be binary search trees.
8+
9+
10+
# Example 1:
11+
# Input: root = [2,1,3]
12+
# Output: true
13+
14+
# Example 2:
15+
# Input: root = [5,1,4,null,null,3,6]
16+
# Output: false
17+
# Explanation: The root node's value is 5 but its right child's value is 4.
18+
19+
20+
# Constraints:
21+
22+
# The number of nodes in the tree is in the range [1, 104].
23+
# -231 <= Node.val <= 231 - 1
24+
25+
26+
from typing import Optional
27+
# Definition for a binary tree node.
28+
class TreeNode:
29+
def __init__(self, val=0, left=None, right=None):
30+
self.val = val
31+
self.left = left
32+
self.right = right
33+
class Solution:
34+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
35+
return self.checkValidity(root, float('-inf'), float('inf'))
36+
37+
def checkValidity(self, node, min_val, max_val):
38+
if not node:
39+
return True
40+
if node.val < min_val or node.val > max_val:
41+
return False
42+
43+
return self.checkValidity(node.left, min_val, node.val - 1) and \
44+
self.checkValidity(node.right, node.val + 1, max_val)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /